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.
// 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
1. Why is 'Execute(object p) => LoadDataAsync();' dangerous when LoadDataAsync is 'async Task'?
2. What mechanism prevents an async command from being triggered twice before the first call completes?
3. Where is 'async void' considered acceptable in idiomatic C# MVVM code?
4. What does CommunityToolkit.Mvvm's IAsyncRelayCommand.ExecutionTask enable?
5. What guarantees an _isExecuting flag resets even if the awaited async operation throws?
Was this page helpful?
You May Also Like
The RelayCommand Pattern
A reusable ICommand implementation that wraps Execute and CanExecute delegates, eliminating the need to write a bespoke command class for every ViewModel action.
The ICommand Interface
The core .NET interface that lets ViewModels expose actions to the View without any code-behind, forming the backbone of command-based interaction in MVVM.
Command Parameters
How CommandParameter passes contextual data from a View control into a ViewModel's Execute and CanExecute logic, and the patterns and pitfalls around its use.
Related Reading
Related Study Notes in Microsoft Technologies
Browse all study notesWindows 10 / UWP Development Study Notes
.NET · 30 topics
Microsoft TechnologiesWindows Batch Scripting Study Notes
Batch · 30 topics
Microsoft TechnologiesMFC (Microsoft Foundation Classes) Study Notes
C++ · 30 topics
Microsoft TechnologiesSilverlight Study Notes
.NET · 30 topics
Microsoft TechnologiesXAML Study Notes
.NET · 30 topics
Microsoft TechnologiesWPF (Windows Presentation Foundation) Study Notes
.NET · 30 topics