Page 129 - CSharp/C#
P. 129
var secondTask = TaskOperation("#secondTask executed");
var thirdTask = TaskOperation("#thirdTask executed");
await Task.WhenAny(firstTask, secondTask, thirdTask);
}
The Task returned by RunConcurrentTasksWhenAny will complete when any of firstTask, secondTask, or
thirdTask completes.
Await operator and async keyword
await operator and async keyword come together:
The asynchronous method in which await is used must be modified by the async
keyword.
The opposite is not always true: you can mark a method as async without using await in its body.
What await actually does is to suspend execution of the code until the awaited task completes; any
task can be awaited.
Note: you cannot await for async method which returns nothing (void).
Actually, the word 'suspends' is a bit misleading because not only the execution stops, but the
thread may become free for executing other operations. Under the hood, await is implemented by
a bit of compiler magic: it splits a method into two parts - before and after await. The latter part is
executed when the awaited task completes.
If we ignore some important details, the compiler roughly does this for you:
public async Task<TResult> DoIt()
{
// do something and acquire someTask of type Task<TSomeResult>
var awaitedResult = await someTask;
// ... do something more and produce result of type TResult
return result;
}
becomes:
public Task<TResult> DoIt()
{
// ...
return someTask.ContinueWith(task => {
var result = ((Task<TSomeResult>)task).Result;
return DoIt_Continuation(result);
});
}
private TResult DoIt_Continuation(TSomeResult awaitedResult)
{
// ...
}
https://riptutorial.com/ 75

