如何等待嵌套任务?

时间:2018-05-23 14:55:08

标签: c# multithreading

假设我有以下情况:

public void Foo()
{
    Task.Run(() => DoWork())
      .ContinueWith((prev) => 
      {
          Console.WriteLine("Hello World!");
      }
}

public void DoWork()
{
    Task.Run(() => HeavyOperation());
    Task.Run(() => HeavyOperation2());
    Task.Run(() => HeavyOperation3());
}

我需要等待DoWork内的所有任务完成后再显示Hello World,实际上我的代码会显示Hello World,但方法内的任务仍在运行

2 个答案:

答案 0 :(得分:5)

您可以使用Task.WhenAll返回等待所有任务的Task

public Task DoWork()
{
    return Task.WhenAll(
        Task.Run(() => HeavyOperation()),
        Task.Run(() => HeavyOperation2()),
        Task.Run(() => HeavyOperation3()));
}

注意:要遵循惯例,您应该调用此DoWorkAsync

public Task DoWorkAsync()
{
    return Task.WhenAll(
        Task.Run(() => HeavyOperation()),
        Task.Run(() => HeavyOperation2()),
        Task.Run(() => HeavyOperation3()));
}

此外,操作已在不同的主题上运行,您不需要Task.Run来调用DoWorkAsync

DoWorkAsync()
    .ContinueWith((prev) => 
    {
        Console.WriteLine("Hello World!");
    };

答案 1 :(得分:0)

您可以在DoWork内使用Task.WaitAll来电。

示例pesudocode

public void DoWork()
{
    var tasks = new List<Task>();
    tasks.Add(Task.Run(() => HeavyOperation()));
    tasks.Add(Task.Run(() => HeavyOperation2()));
    tasks.Add(Task.Run(() => HeavyOperation3()));

    Task.WaitAll(tasks.ToArray());
}