Marquer une méthode async
Contexte : Ajoutez le modificateur async à toute méthode qui utilise await. La méthode doit retourner Task, Task<T>, ValueTask, ValueTask<T> ou void.
using System.Threading.Tasks;
public class Example{ public async Task DoWorkAsync() { await Task.Delay(100); }
public async Task<int> GetNumberAsync() { await Task.Delay(100); return 42; }}- Les méthodes
asyncpeuvent contenirawaità l’intérieur. - Le compilateur transforme la méthode en machine à états.
- Les noms de paramètres ne peuvent pas être
await(sauf échappement avec@await).
Exemple d’utilisation dans le monde réel
Section intitulée « Exemple d’utilisation dans le monde réel »Application console : Marquez Main comme async Task (C# 7.1+).
using System.Threading.Tasks;
class Program{ static async Task Main(string[] args) { await DownloadAsync(); }
static async Task DownloadAsync() => await Task.Delay(100);}Exemple : async Main en C#