100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
.NET

Async Commands

How to correctly implement ICommand for asynchronous operations without deadlocks, unobserved exceptions, or double-execution, including the AsyncRelayCommand pattern.

CommandsAdvanced11 min readJul 10, 2026
Analogies

Why async void Execute Is Dangerous

ICommand.Execute returns void, so a naive implementation that calls an async method directly, like 'Execute(object p) => LoadDataAsync()' where LoadDataAsync is 'async Task', silently discards the returned Task, meaning any exception thrown inside LoadDataAsync becomes an unobserved task exception that can crash the process on the finalizer thread in older .NET versions, or simply vanish unnoticed in newer ones. This 'async void'-style fire-and-forget pattern also means CanExecute has no reliable signal that an operation is still in flight, so a user can click Save five times in a row before the first save even completes, unless the command explicitly tracks its own busy state.

🏏

Cricket analogy: It's like a fielder throwing the ball toward the stumps for a run-out without ever checking if it actually hit, walking away regardless, the way a fire-and-forget async Execute discards the Task and never checks whether the operation actually succeeded.

csharp
// Dangerous: fire-and-forget, exceptions are unobserved
public void Execute(object parameter) => LoadDataAsync();

// Safer: AsyncRelayCommand tracks execution state and observes exceptions
public class AsyncRelayCommand : ICommand
{
    private readonly Func<Task> _executeAsync;
    private readonly Func<bool> _canExecute;
    private bool _isExecuting;

    public AsyncRelayCommand(Func<Task> executeAsync, Func<bool> canExecute = null)
    {
        _executeAsync = executeAsync;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter) =>
        !_isExecuting && (_canExecute?.Invoke() ?? true);

    public async void Execute(object parameter) => await ExecuteAsync();

    public async Task ExecuteAsync()
    {
        _isExecuting = true;
        RaiseCanExecuteChanged();
        try
        {
            await _executeAsync();
        }
        catch (Exception ex)
        {
            // Log, or surface via an ErrorMessage property bound in the View
            LastException = ex;
        }
        finally
        {
            _isExecuting = false;
            RaiseCanExecuteChanged();
        }
    }

    public Exception LastException { get; private set; }

    public event EventHandler CanExecuteChanged;
    public void RaiseCanExecuteChanged() =>
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}

Tracking Busy State to Prevent Double-Execution

The core fix is maintaining an _isExecuting flag that CanExecute checks and that flips back and forth around the awaited call inside a try/finally block, guaranteeing the flag resets even if the operation throws. Because Execute must still return void to satisfy ICommand, the implementation wraps the real async logic in a separately awaitable ExecuteAsync() method, letting code that already has an async context, like a keyboard shortcut handler, await it directly, while the ICommand.Execute entry point uses 'async void' only at this one deliberate boundary, which is the sole place async void is considered acceptable in idiomatic C#.

🏏

Cricket analogy: It's like a stadium's electronic gate lock: once a turnstile is mid-cycle for one spectator, it physically can't be triggered again until the mechanism resets, exactly like CanExecute returning false while _isExecuting blocks a second Save click.

Toolkit Support: IAsyncRelayCommand

CommunityToolkit.Mvvm ships AsyncRelayCommand and the [RelayCommand] attribute both support async Task-returning methods directly, automatically generating an IAsyncRelayCommand that exposes an ExecutionTask property you can bind a ProgressBar's Visibility to, plus configurable AwaitBehavior (like Concurrent or Reset) governing what happens if the command is invoked again while already running. This removes the need to hand-write the try/finally busy-flag dance shown above for the vast majority of everyday cases, while still allowing IsCancellable/IAsyncRelayCommand<T> variants for operations that need CancellationToken support.

🏏

Cricket analogy: It's like a franchise adopting the BCCI's standardized DRS software instead of each stadium hand-building its own review timer and signal logic, the toolkit's AwaitBehavior playing the role of a league-wide standardized protocol.

IAsyncRelayCommand.ExecutionTask is especially useful for binding a busy-spinner: 'Visibility={Binding SaveCommand.ExecutionTask.IsCompleted, Converter={StaticResource InverseBoolToVisibility}}' shows a spinner exactly while the command's task is still running, without any manual IsBusy property.

Using 'async void Execute' anywhere outside the single ICommand entry-point boundary is an anti-pattern: exceptions thrown from an async void method cannot be caught by a surrounding try/catch at the call site and will propagate to SynchronizationContext.Post, typically crashing the application if unhandled.

  • ICommand.Execute must return void, but naive 'async Task' fire-and-forget calls silently drop exceptions.
  • An _isExecuting flag checked by CanExecute prevents double-execution while an async command is in flight.
  • try/finally around the awaited call guarantees the busy flag resets even when the operation throws.
  • 'async void' is only acceptable at the single ICommand.Execute entry-point boundary, never deeper in the call chain.
  • CommunityToolkit.Mvvm's AsyncRelayCommand/[RelayCommand] handle async Task methods and busy-tracking automatically.
  • IAsyncRelayCommand.ExecutionTask can be bound directly to drive busy spinners without a manual IsBusy property.
  • AwaitBehavior options like Concurrent or Reset control what happens if a command is re-invoked while running.

Practice what you learned

Was this page helpful?

Topics covered

#NET#MVVMDesignPatternStudyNotes#MicrosoftTechnologies#AsyncCommands#Async#Commands#Void#Execute#Concurrency#StudyNotes#SkillVeris