Marking method async
Context: Add the async modifier to any method that uses await. The method must return Task, Task<T>, ValueTask, ValueTask<T>, or 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; }}asyncmethods can haveawaitinside.- The compiler transforms the method into a state machine.
- Parameter names cannot be
await(unless escaped with@await).
Real-world usage example
Section titled “Real-world usage example”Console application: Mark Main as 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);}Example: async Main in C#