Aller au contenu

Threads et async

L'interface ne se modifie que depuis le thread UI. Le travail long se fait ailleurs.

Pourquoi c'est important

Le thread UI dessine l'interface et traite les clics. S'il est occupé, l'application gèle.

❌ appel bloquant Thread UI Charger() : 3 s, interface gelée ✅ await Thread UI libre : clics, animations OK Arrière-plan requête réseau / Task.Run mise à jourmise à jour

async / await : le cas courant

private async void OnCharger(object? sender, RoutedEventArgs e)
{
    Bouton.IsEnabled = false;
    try
    {
        var donnees = await _api.GetCommandesAsync();   // ne bloque pas l'UI
        Liste.ItemsSource = donnees;                    // retour sur le thread UI
    }
    finally
    {
        Bouton.IsEnabled = true;
    }
}

Après un await lancé depuis le thread UI, la suite reprend sur le thread UI.

Calcul lourd

var resultat = await Task.Run(() => CalculerStatistiques(gigaListe));
Resume.Text = resultat.ToString();

Revenir sur le thread UI

sequenceDiagram
  participant BG as Thread d'arrière-plan
  participant D as Dispatcher.UIThread (file d'attente)
  participant UI as Thread UI
  BG->>D: Post(() => Statut.Text = "Terminé")
  Note over BG: continue sans attendre
  D->>UI: exécute quand le thread UI est libre
  UI->>UI: Statut.Text = "Terminé" ✔
using Avalonia.Threading;

// Sans attendre
Dispatcher.UIThread.Post(() => Statut.Text = "Terminé");

// En attendant le résultat
var largeur = await Dispatcher.UIThread.InvokeAsync(() => Bounds.Width);

// Suis-je sur le thread UI ?
if (!Dispatcher.UIThread.CheckAccess())
    Dispatcher.UIThread.Post(MettreAJour);

Priorité

Dispatcher.UIThread.Post(() => DessinerApercu(), DispatcherPriority.Background);

Progression

var progres = new Progress<int>(p => Barre.Value = p);   // créé sur le thread UI
await Task.Run(() => Importer(fichiers, progres));

Annulation

Chaque frappe annule la recherche précédente : seule la dernière va au bout (anti-rebond).

sequenceDiagram
  participant U as Utilisateur
  participant R as Recherche
  U->>R: tape « a » → lance (attente 300 ms)
  U->>R: tape « av » → annule « a », relance
  U->>R: tape « ava » → annule « av », relance
  Note over R: 300 ms sans frappe
  R-->>U: résultats pour « ava » uniquement
private CancellationTokenSource? _cts;

private async void OnRechercher(object? sender, TextChangedEventArgs e)
{
    _cts?.Cancel();
    _cts = new CancellationTokenSource();
    var jeton = _cts.Token;

    try
    {
        await Task.Delay(300, jeton);   // anti-rebond
        Resultats.ItemsSource = await _service.RechercherAsync(Recherche.Text, jeton);
    }
    catch (OperationCanceledException) { }
}

DispatcherTimer

var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) };
timer.Tick += (_, _) => Horloge.Text = DateTime.Now.ToString("HH:mm:ss");
timer.Start();

Version courte :

var abonnement = DispatcherTimer.Run(() =>
{
    Horloge.Text = DateTime.Now.ToString("HH:mm:ss");
    return true;   // false = arrêter
}, TimeSpan.FromSeconds(1));

// abonnement.Dispose() pour arrêter

v12

DispatcherTimer utilise le dispatcher du thread où il est créé. Créez-le sur le thread UI (dans un constructeur de vue, un gestionnaire d'événement…), pas dans un Task.Run.

Plusieurs dispatchers v12

Avalonia 12 permet un dispatcher par thread.

Dispatcher.UIThread;           // thread UI principal : toujours valide
Dispatcher.CurrentDispatcher;  // dispatcher du thread courant
monControle.Dispatcher;        // dispatcher qui possède ce contrôle

Dans une bibliothèque de contrôles, préférez monControle.Dispatcher à Dispatcher.UIThread.

Erreurs dans les async void

private async void OnClic(object? sender, RoutedEventArgs e)
{
    try
    {
        await FaireQuelqueChoseAsync();
    }
    catch (Exception ex)
    {
        Erreur.Text = ex.Message;   // sinon l'exception plante l'application
    }
}

Filet de sécurité global :

Dispatcher.UIThread.UnhandledException += (_, e) =>
{
    Journal.Erreur(e.Exception);
    e.Handled = true;
};