After a lot of readings about await/async, I still have some misunderstanding about the subject. Please provide a short answer (yes/no) and a long answer to my questions, so I can have better understanding.
Let's say we have the following method:
public async Task UnresultTaskMethod()
{
await AsyncMethod1();
await AsyncMethod2();
}
Questions:
Task.WaitAll(tasks); Task.WhenAll(tasks);
Task.WaitAll(tasks); Task.WhenAll(tasks);
at the end so I can make sure the execution will not continue before all the tasks have ended, this is the main factor of confusion for me, why to wait for a task in this way if you can wait for them by keyword await?await roughly means 'wait until completed'
No
No
If you don't await, it might be the case, for example
public async Task UnresultTaskMethod()
{
Task.Delay(2000);
// We haven't awaited, so we're here right away
await AsyncMethod2();
}
Task.WaitAll
and Task.WhenAll
don't make sense when you await individual tasks right away. However, you can do this:public async Task UnresultTaskMethod()
{
var task1 = AsyncMethod1();
var task2 = AsyncMethod2();
// The tasks are now doing their job
await Task.WhenAll(task1, task2);
// Here you are sure both task1 and task2 are completed
}
With Task.WaitAll
it would be like this:
public async Task UnresultTaskMethod()
{
var task1 = AsyncMethod1();
var task2 = AsyncMethod2();
// This is not awaitable, you're blocking the current thread
Task.WaitAll(task1, task2);
// Here you are sure both task1 and task2 are completed
}
In this case, you don't need async Task
, because you are not awaiting, ie it is effectively a void
method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.