Comment et quand utiliser 'async' et 'await'

Comment et quand utiliser ‘async’ et ‘await’

Lorsque vous utilisez async et await, le compilateur génère une machine à états en arrière-plan.

Voici un exemple avec lequel j’espère pouvoir expliquer certains des détails de haut niveau de ce qui se passe :

public async Task MyMethodAsync()
{
    Task<int> longRunningTask = LongRunningOperationAsync();
    // independent work which doesn't need the result of LongRunningOperationAsync can be done here

    //and now we call await on the task
    int result = await longRunningTask;
    //use the result
    Console.WriteLine(result);
}

public async Task<int> LongRunningOperationAsync() // assume we return an int from this long running operation
{
    await Task.Delay(1000); // 1 second delay
    return 1;
}

Bien, alors que se passe-t-il ici :

Task<int> longRunningTask = LongRunningOperationAsync(); commence l’exécution de LongRunningOperation

Un travail indépendant est effectué sur, supposons, le thread principal (Thread ID = 1) puis await longRunningTask est atteint.

Maintenant, si longRunningTask n’est pas terminé et est toujours en cours d’exécution, MyMethodAsync() retournera à sa méthode appelante, ainsi le thread principal n’est pas bloqué. Lorsque longRunningTask est terminé, un thread du ThreadPool (qui peut être n’importe quel thread) retournera à MyMethodAsync() dans son contexte précédent et continuera l’exécution (dans ce cas, l’affichage du résultat dans la console).

Un second cas serait que longRunningTask ait déjà terminé son exécution et que le résultat soit disponible. En atteignant await longRunningTask, nous avons déjà le résultat donc le code continuera à s’exécuter sur le même thread. (dans ce cas, l’affichage du résultat dans la console). Bien sûr, ce n’est pas le cas pour l’exemple ci-dessus, où il y a un Task.Delay(1000) impliqué.