如果我得到以下代码段:
async Task MyFunc()
{
await DoWork1();
await DoWork2();
}
async Task<object> DoWork1() { /*Do work here*/ }
async Task<object> DoWork2() { /*Do other work here*/ }
void main()
{
MyTask();
//Do some stuff which needs MyFunc() to be completed beforehand.
}
我想要做的是让DoWork1()和DoWork2()并行运行但是如果它们都已完成则只返回main()。
它会那样工作吗?还是有更好的解决方案?
答案 0 :(得分:1)
您可以使用WhenAll
进行简单的并行操作:
async Task MyFunc()
{
var task1 = DoWork1();
var task2 = DoWork2();
await Task.WhenAll(task1, task2);
}