Task Parallel Library - Know when all tasks are fi

2019-06-22 05:58发布

I use Task Parallel Library to start some tasks, like so:

    public static void Main()
    {
        for (var i = 0; i < 10; i++)
        {
            var x = i;
            Task.Factory.StartNew(() => new WorkerClass(x).Do());
        }

        // (*) Here I'd like to wait for all tasks to finish
        Task.WaitAll(); 

        Console.WriteLine("Ready.");
        Console.ReadLine();
    }

The problem is that some tasks can create new tasks themselves. This is how WorkerClass looks like:

public class WorkerClass
{
    private static readonly NLog.Logger Log = NLog.LogManager.GetCurrentClassLogger();

    private readonly int _i;

    public WorkerClass(int i)
    {
        _i = i;
    }

    public void Do()
    {
        if (_i % 3 == 0)
            Task.Factory.StartNew(() => new WorkerClass(_i + 101).Do());

        Log.Info("Started {0}", _i);
        Thread.Sleep(2000);
        Log.Info("Done {0}", _i);
    }
}

For every value of i that's a multiple of 3, a new Task is started.

I'd like to be able to wait until all tasks (including the ones created by other tasks) are finished.

Is there a clean/built-in way to do this (with or without TPL)?

1条回答
乱世女痞
2楼-- · 2019-06-22 06:24

Keep a reference to all top-level tasks and then just use WaitAll:

    var tasks = new Task[10];
    for (var i = 0; i < 10; i++)
    {
        var x = i;
        tasks[i] = Task.Factory.StartNew(() => new WorkerClass(x).Do());
    }

    Task.WaitAll( tasks );

As for the child tasks, just make sure you attach them to the parent task. This means that the parent task will not go into a complete state until all child tasks are also finished.

    Task.Factory.StartNew(() => { }, TaskCreationOptions.AttachedToParent);
查看更多
登录 后发表回答