AsyncDelegateCommand Decorator – use your own ICommand implementation

In my last post I introduced an implementation of the System.Windows.Input.ICommand interface that enables us to use the new .NET 4.5 async & await feature. Since there may be lot of customized ICommand implementations around, I find it would make sense to have a Decorator that takes any other ICommand implementation and enables it to be used asynchronously. Based on the AsyncDelegateCommand implementation from my last post, it is just a few lines of code to implement the decorator.

public class AsynchronizingCommandDecorator : AsyncDelegateCommand
{
    public AsynchronizingCommandDecorator(ICommand otherCommandImpl)
        : base(null, otherCommandImpl.CanExecute)
    {
        Action<object> syncExecute = otherCommandImpl.Execute;

        _asyncExecute =
            async o =>
            {
                await Task.Factory.FromAsync<object>(syncExecute.BeginInvoke, syncExecute.EndInvoke, o, null);
            };
    }
}

Just wrap the synchronous command’s Execute method into an async delegate that starts a new task. Done.

Although this looks pretty simple at the surface, there are some things to consider before using it. If the synchronous commands have updated the UI before (or caused other changes that did that in turn), you will now get exceptions thrown at you, since those changes (of the UI) are no longer executing on the UI thread, but on the Task that has been started. In such a case you can either dispatch the UI updates to the UI thread (by using the Dispatcher) or just keep the synchronous commands.

In the next post I am going to add the next little bit to the asynchronous command infrastructure. Equipped with our asynchronous command, we can now easily connect a BusyIndicator that is automatically triggered on asynchronous operations.

I really appreciate your ideas and feedback on this. See you…

Leave a Reply

Your email address will not be published. Required fields are marked *