# 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 view-model actions. Keep command bodies focused, delegate large workflows to services, keep `CanExecute` cheap, and refresh it only when relevant state changes. * 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. * Use `async void` only for true event handlers, and wrap their bodies in `try`/`catch` (see the C# async rule). ## Async and Threading * Follow the C# async rule; in WPF, never block the UI thread, run I/O asynchronously, and move measured CPU-heavy work off it. * 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. * Cancel obsolete work when views or selections change, prevent overlapping operations from overwriting newer results, and handle exceptions from background work 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 * Unsubscribe from long-lived publishers, or use `WeakEventManager` where the publisher lives much longer than the subscriber, to prevent leaks. * Keep event handlers small, and do not use events as hidden global communication channels or long chains.