Module 2 · Lesson 06 of 16
Work that doesn't freeze the window
Async commands keep the UI thread free. Cancellation is a button, not a dead process, and the busy state is data.
The UI thread runs the message loop. If you block it, the window stops painting,
stops responding, and the operating system eventually offers to kill it. await
is how you leave the thread without leaving the method.
The command
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace CourseApp.Lessons.Async;
public sealed record RepositoryItem(string Name, int Stars);
public partial class AsyncViewModel : ObservableObject
{
readonly Func<CancellationToken, Task<IReadOnlyList<RepositoryItem>>> _load;
public AsyncViewModel(Func<CancellationToken, Task<IReadOnlyList<RepositoryItem>>>? load = null) =>
_load = load ?? FakeLoad;
public ObservableCollection<RepositoryItem> Results { get; } = [];
[ObservableProperty]
private bool _isBusy;
[ObservableProperty]
private string _status = "Idle. Nothing has been requested.";
[RelayCommand(CanExecute = nameof(CanLoad), IncludeCancelCommand = true)]
private async Task LoadAsync(CancellationToken token)
{
IsBusy = true;
Status = "Loading…";
try
{
var items = await _load(token);
Results.Clear();
foreach (var item in items)
Results.Add(item);
Status = $"Loaded {items.Count} repositories.";
}
catch (OperationCanceledException)
{
Status = "Cancelled. The window stayed responsive the whole time.";
}
finally
{
IsBusy = false;
}
}
bool CanLoad() => !IsBusy;
static async Task<IReadOnlyList<RepositoryItem>> FakeLoad(CancellationToken token)
{
await Task.Delay(900, token);
return
[
new("Avalonia", 26_400),
new("CommunityToolkit.Mvvm", 5_900),
new("ReactiveUI", 8_100),
];
}
}
[RelayCommand] on a Task-returning method generates an IAsyncRelayCommand.
IsRunning is built in; CanExecute can consult it. Adding
IncludeCancelCommand = true generates a second command that cancels the
CancellationToken passed to your method.
The loader is a constructor parameter with a default:
public AsyncViewModel(Func<CancellationToken, Task<IReadOnlyList<RepositoryItem>>>? load = null)
That is the seam the verifier uses. The sample ships a fake that waits 900 ms; the test passes a completed task and runs in microseconds. Same class, no window, no network.
Where the continuation runs
After await, execution resumes on the captured synchronization context — the
Avalonia dispatcher — so touching Results or IsBusy is safe. The framework
takes care of this; you do not need Dispatcher.UIThread.InvokeAsync for ordinary
await continuations.
You do need it when work finishes on a thread you started yourself:
var items = await Task.Run(() => ReadHugeFile(path)); // resumes on the UI thread
Never
.Resultor.Wait()on the UI thread. It deadlocks: the continuation needs the thread that is blocked waiting for it. The sample's verifier is allowed to block because it runs headless with no message loop; production code is not.
Cancellation and errors
- Catch
OperationCanceledExceptionand say so in the UI. A cancelled load is not a failure. - Reset the busy flag in
finally, or the next attempt can never start. - Unhandled exceptions from an async command surface on the UI thread. Handle the ones you expect; let a global handler report the rest.
Try it
- Make the fake loader throw on every third call and show an error state.
- Disable the list while loading, then re-enable it in
finally. - Replace the fake with a real HTTP call behind
HttpClient. The view model does not change — which is the point of the seam.
Files this lesson draws from
src/CourseApp/Lessons/06_Async/AsyncViewModel.cssrc/CourseApp/Lessons/06_Async/AsyncView.axaml
VerifiedThe verifier injects a fake loader, executes LoadAsync, and asserts two results arrived, the busy flag cleared, and the status reflects a successful load.