They consist of two main keywords- async and await. async is used to make a function asynchronous. When using async and await the compiler generates a state machine in the background. Here’s an example on which I hope I can explain some of the high-level details that are going on:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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; } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.