How to use async and await in c#?
The async
and await
keywords in C# enable asynchronous programming, allowing you to perform long-running operations without blocking the main thread.
Example:
public async Task LongRunningOperation()
{
await Task.Delay(1000);
return 1;
}
Solution:
With the async
keyword, you can define an asynchronous method, and the await
keyword indicates a point in the method where it'll asynchronously wait for the task to complete:
int result = await LongRunningOperation();
Console.WriteLine(result); // Outputs: 1