Skip to main content
A newer version of this page is available. .

Asynchronous Commands

  • 4 minutes to read

Asynchronous commands can be useful if you need to run a time-consuming operation in a separate thread without freezing the UI. For instance, if you need to calculate something, you can bind a button to an asynchronous command. When an end-user clicks the button, the command starts the calculation process and the button becomes disabled. When the process is done, the button is enabled.

The following asynchronous commands are available.

  • AsyncCommand<T> - Specifies a command whose Execute and CanExecute delegates accept a single parameter of type T.
  • AsyncCommand - Specifies a command whose Execute and CanExecute delegates do not have any parameters.

Creating AsyncCommands

The AsyncCommand and AsyncCommand<T> can be created similarly to the regular Delegate Commands. There are two constructors: a constructor that accepts the Execute delegate, and a second constructor that accepts Execute and CanExecute delegates. The Execute delegate should return a Task object. Similar to Delegate Commands, the AsyncCommand constructors support the optional useCommandManager parameter (which equals True by default) that specifies whether the CommandManager is used to raise the CanExecuteChanged event.

AsyncCommand<string> myAsyncCommand = new AsyncCommand<string>(Calculate, CanCalculate, true);
Task Calculate(string parameter) {
    return Task.Factory.StartNew(CalculateCore);
}
bool CanCalculate(string parameter) {
    //...
}
void CalculateCore() {
    //...
}

Running AsyncCommands

You can bind to AsyncCommands in the same manner as any ICommand.

<Button Content="..." Command="{Binding MyAsyncCommand}"/>
<Button Content="..." Command="{Binding MyAsyncCommand}" CommandParameter="..."/>

Preventing Simultaneous Execution

The AsyncCommand and AsyncCommand<T> classes provide the IsExecuting property. While the command execution task is working, this property equals True and the AsyncCommand.CanExecute method always returns False, no matter what you implemented in the CanExecute delegate. This feature allows you to disable a control bound to the command until the previous command execution is completed.

You can disable this behavior by setting the AsyncCommand.AllowMultipleExecution property to True. In this case, the AsyncCommand.CanExecute method returns a value based on your CanExecute delegate implementation.

Canceling Command Executions

The AsynCommands provide the IsCancellationRequested property, which you can check in the execution method to implement canceling the command execution.

AsyncCommand myAsyncCommand = new AsyncCommand(Calculate);
Task Calculate() {
    return Task.Factory.StartNew(CalculateCore);
}
void CalculateCore() {
    for(int i = 0; i <= 100; i++) {
        if(myAsyncCommand.IsCancellationRequested) return;
        Progress = i;
        Thread.Sleep(TimeSpan.FromSeconds(0.1));
    }
}

The AsyncCommand.IsCancellationRequested property is set to True when AsyncCommand.CancelCommand is invoked. You can bind a control to the CancelCommand as follows.

<StackPanel Orientation="Vertical">
    <ProgressBar Minimum="0" Maximum="100" Value="{Binding Progress}" Height="20"/>
    <Button Content="Calculate" Command="{Binding MyAsyncCommand}"/>
    <Button Content="Cancel" Command="{Binding MyAsyncCommand.CancelCommand}"/>
</StackPanel>

If you need more control of the cancellation process, use the AsyncCommand.CancellationTokenSource property. For instance:

AsyncCommand myAsyncCommand = new AsyncCommand(Calculate);
Task Calculate() {
    return Task.Factory.StartNew(CalculateCore, myAsyncCommand.CancellationTokenSource.Token).
        ContinueWith(x => MessageBoxService.Show(x.IsCanceled.ToString()));
}
void CalculateCore() {
    for(int i = 0; i <= 100; i++) {
        myAsyncCommand.CancellationTokenSource.Token.ThrowIfCancellationRequested();
        Progress = i;
        Thread.Sleep(TimeSpan.FromSeconds(0.1));
    }
}

AsyncCommands and IDispatcherService

If it is required that you report progress (update the UI) from the execution process to the main thread, use the IDispatcherService as follows.

IDispatcherService DispatcherService { get { ... } }
void CalculateCore() {
    ...
    DispatcherService.BeginInvoke(() => {
        ...
    });
    ...
}

AsyncCommands in POCO

POCO provides the capability to automatically create AsyncCommands based on a public function returning a Task object (the function should have one parameter or be parameterless). To access the IsExecuting and IsCancellationRequested command properties, you can use the DevExpress.Mvvm.POCO.POCOViewModelExtensions class, which provides the GetAsyncCommand method. Below is an example of a POCO ViewModel that creates an async CalculateCommand for the Calculate method.

[POCOViewModel]
public class ViewModel {
    public virtual int Progress { get; set; }
    public Task Calculate() {
        return Task.Factory.StartNew(CalculateCore);
    }
    void CalculateCore() {
        for(int i = 0; i <= 100; i++) {
            if(this.GetAsyncCommand(x => x.Calculate()).IsCancellationRequested) return;
            Progress = i;
            Thread.Sleep(TimeSpan.FromSeconds(0.1));
        }
    }
}