# WPF Commands, Async, and Threading Apply these rules when implementing commands, async operations, UI-thread work, or event subscriptions in WPF. ## Commands * Prefer commands over click handlers for ViewModel-driven actions. * Keep command execution focused. * Avoid putting large workflows directly inside command implementations. * Keep `CanExecute` logic cheap. * Refresh command availability only when relevant state changes. * Avoid command implementations with hidden side effects. * Implement async commands with the project's MVVM library (for example CommunityToolkit.Mvvm `AsyncRelayCommand` or `[RelayCommand]`): disable re-entry unless concurrent runs are intended, expose cancellation for long operations, and surface failures to the user. * Never use `async void` except for true event handlers. ## Async and Threading * Keep async operations asynchronous throughout the call chain. * Avoid `.Result`, `.Wait()` and other synchronous blocking of async work. * Do not block the UI thread. * Run I/O asynchronously. * Move expensive CPU work off the UI thread only when necessary. * Let `await` resume on the UI thread in view models instead of calling the Dispatcher. When marshaling is unavoidable, inject a dispatcher abstraction; never use `Application.Current.Dispatcher` in view models, which breaks testing without a UI thread. * Do not use the Dispatcher to hide incorrect threading design. * Support `CancellationToken` for cancellable long-running operations. * Cancel obsolete work when views or selections change. * Prevent race conditions caused by overlapping async operations. * Handle exceptions from background operations explicitly. ## UI Thread * Treat the UI thread as a scarce resource: no I/O, parsing, serialization, database, or network work on it. * Batch UI updates and avoid updating bound collections in tight loops; see the collections rule for bulk changes. * Keep rendering-related callbacks lightweight. ## Events * Avoid unnecessary event subscriptions. * Unsubscribe from long-lived publishers when required. * Prevent memory leaks from event handlers. * Use `WeakEventManager` where the publisher lives significantly longer than the subscriber. * Keep event handlers small. * Do not use events as hidden global communication channels. * Avoid excessive event chaining.