完成后重新启动数组中的所有任务

时间:2013-05-27 06:24:02

标签: c# winforms task-parallel-library

我有一个子任务数组,它们执行一个方法,一旦完成一个工作,我会得到一个通知,然后结束。现在我希望他们重新开始同样的工作,没有任何麻烦。这怎么可能?

这就是我创建任务数组和处理任务完成的方式:

public void Start()
        {

            this.totalRangePerThread = ((this.endRange - this.startRange) / this.subTasks.Length);

            for (int i = 0; i < this.subTasks.Length; ++i)
            {
                var copy = startRange;
                this.subTasks[i] = new Task(() => searchItem(copy, this.totalRangePerThread), this.token, TaskCreationOptions.LongRunning);
                this.startRange = this.startRange + this.totalRangePerThread;
            }

            //start tasks
            for (int taskIndex = 0; taskIndex < this.subTasks.Length; ++taskIndex)
            {
                    this.subTasks[taskIndex].Start();     
            }
            Task.Factory.ContinueWhenAll(this.subTasks, completedTasks =>
            {
                //write it onto the the activitylog
                if (Form1.Instance != null)
                {
                    Form1.Instance.BeginInvoke((MethodInvoker)delegate
                    {
                        Form1.Instance.AddItemtoActivityLog("Search Completed!");
                    });
                }
            });

        }

我应该再次调用Start()方法,还是有一种神奇地重启子任务的机制?

2 个答案:

答案 0 :(得分:1)

public void Start()
{
    var yourTasks = new Task[] {
    Task.Factory.StartNew(_ => task1(),
    Task.Factory.StartNew(_ => task2(),
    Task.Factory.StartNew(_ => ...
    Task.Factory.StartNew(_ => taskN() };
    Task.WaitAll(yourTasks ); // wait for all N tasks to complete
    Start();
}

答案 1 :(得分:1)

您可以将用于准备和执行子任务的代码提取到单独的方法中。然后在Start()方法中将其调用两次:

private void ExecuteSubTasks()
{
    var tasks = new Task[]
        {
            new Task(() => Console.WriteLine("SubTask1 executed.")),
            new Task(() => Console.WriteLine("SubTask2 executed.")),
            new Task(() => Console.WriteLine("SubTask3 executed.")),
        };

    foreach (var task in tasks)
        task.Start();
    Task.WaitAll(tasks);
}

private void Start()
{
    var mainTask = Task.Factory.StartNew(() => ExecuteSubTasks())
        .ContinueWith((prev) =>
        {
            ExecuteSubTasks();
            this.Invoke((MethodInvoker)delegate { MessageBox.Show("Completed."); });
        });
}