# Async work and the UI thread

Show a useful loading state while work runs, then ignore its result if the page has gone away. The tricky part is not `await`; it is deciding whether the result still belongs to this view.

This label accepts a loader and the runtime's UI dispatcher. It starts when activated and cancels when deactivated. The loader can read a file, call a service, or use a deterministic fake in a test.

```csharp
using System;
using System.Threading;
using System.Threading.Tasks;
using Xui.Core.Actual;
using Xui.Core.UI;

public sealed class AsyncStatus : Label
{
    private readonly IDispatcher dispatcher;
    private readonly Func<CancellationToken, Task<string>> load;
    private CancellationTokenSource? request;
    public AsyncStatus(IDispatcher dispatcher, Func<CancellationToken, Task<string>> load)
    {
        this.dispatcher = dispatcher;
        this.load = load;
        Text = "Waiting to open";
    }

    protected override void OnActivate()
    {
        base.OnActivate();
        Text = "Loading...";
        var current = new CancellationTokenSource();
        request = current;
        _ = LoadAsync(current);
    }

    private async Task LoadAsync(CancellationTokenSource current)
    {
        var token = current.Token;
        try
        {
            var result = await load(token).ConfigureAwait(false);
            dispatcher.Post(() =>
            {
                if (ReferenceEquals(request, current))
                    Text = result;
            });
        }
        catch (OperationCanceledException)when (token.IsCancellationRequested)
        {
        }
        catch (Exception)
        {
            dispatcher.Post(() =>
            {
                if (ReferenceEquals(request, current))
                    Text = "Could not load. Reopen to retry.";
            });
        }
    }

    protected override void OnDeactivate()
    {
        var old = request;
        request = null; // Reject a completion already queued on the UI thread.
        old?.Cancel();
        old?.Dispose();
        base.OnDeactivate();
    }
}
```

## Supply the operation

Construct `AsyncStatus` with `runtime.MainDispatcher` and a `Func<CancellationToken, Task<string>>`. For a quick local experiment, the loader can await `Task.Delay(1000, token)` and return `"Loaded"`. For production data, pass the token into the actual I/O call and format a small display result.

The class owns the token source. Every activation gets a distinct source; the queued callback compares its identity with the current request. This prevents an old completion from replacing newer page state. Checking cancellation before `Post` would not be enough: navigation could happen after that check but before the callback executes.

The example displays errors instead of letting an unobserved background task fail silently. Add application logging in the catch block if you need diagnostics. Keep user-facing messages short and avoid exposing credentials or server response bodies.

## Keep UI work on its owner thread

`ConfigureAwait(false)` permits the loader continuation to run away from the UI context. Every resulting `Text` assignment goes through `IDispatcher.Post`. Label properties then perform normal invalidation.

`async` does not automatically move CPU work off the UI thread. A synchronous loop before the first await still blocks it. For CPU-heavy work, use a supported worker mechanism and return plain data. The current browser host runs single-threaded WebAssembly; do not assume `Task.Run` creates a browser worker or makes a long calculation harmless.

## Stop work promptly

Deactivation clears the current request before cancelling it. Even a loader that ignores cancellation cannot publish a stale result through this class. Cancellation remains cooperative: the operation must observe its token to stop doing work.

Keep cancellation callbacks fast and nonthrowing. Do not block with `.Wait()` or `.Result` on the UI thread; the operation may need the same dispatcher to finish. For shared subscriptions and resources, continue with [Own and release resources](../resources/index.md).
