如何评估是否有未完成的并行任务并等待它们完成几个冲刺?

时间:2018-08-30 11:30:26

标签: c# multithreading

我有两个任务无法完成,直到它们都完成了两个阶段的\ sprint,而task1的阶段完成并不快,应该等待下一个阶段移至task2之前完成

是否有一种优雅的方法可以让sprint通知并行线程完成?而不将task1task2分成许多小任务。

为了说明

考虑两个对手的接力比赛,但只有一个区别:每次第一个对手团队移动棒子时,他们都等待另一只对手团队移动棒子,然后才继续前进。< / p>

示例:

public static void task1() 
{
    Console.WriteLine("Start of sprint 1");
    //Need to wait for task2 to complete sprint1 and proceed.
    Console.WriteLine("End of sprint 1");

    Console.WriteLine("Start of sprint 2");
    //Need to wait for task2 to complete sprint2 and proceed.
    Console.WriteLine("End of sprint 2");

    //etc... sprint N
}

public static void task2()
{
    Console.WriteLine("Start of sprint 1");
    Thread.Sleep(2000);
    Console.WriteLine("End of sprint 1");

    Console.WriteLine("Start of sprint 2");
    Thread.Sleep(2000);
    Console.WriteLine("End of sprint 2");

    //etc... sprint N
}

//Main thread:
var task1 = Task.Factory.StartNew(Task1);
var task2 = Task.Factory.StartNew(Task2);

//wait for task1 and task2 to be finished with waitAll(new[] {task1, task2})...

1 个答案:

答案 0 :(得分:0)

最后使用Barrier类。

MSDN定义:

  

障碍是用户定义的同步原语,它启用   多个线程(称为参与者)在一个线程上同时工作   算法分阶段进行。 ...

基本用法:

static barrier = new Barrier(N, (sprint) => { Console.WriteLine($"Current sprint: {sprint.CurrentPhaseNumber}");

然后在每次我们希望快速任务等待刚刚添加的慢速任务时

barrier.SignalAndWait();

示例:

static Barrier barrier = new Barrier(2, (bar) =>
{
  Console.WriteLine($"Current sprint number: {bar.CurrentPhaseNumber}.");
});

public static void task1() 
{
    Console.WriteLine("Start of sprint 1 (task1)");
    barrier.SignalAndWait(); //Need to wait for task2 to complete sprint1 and proceed.
    Console.WriteLine("End of sprint 1 (task1)");

    Console.WriteLine("Start of sprint 2 (task1)");
    barrier.SignalAndWait(); //Need to wait for task2 to complete sprint2 and proceed.
    Console.WriteLine("End of sprint 2 (task1)");
}

public static void task2()
{
    Console.WriteLine("Start of sprint 1 (task2)");
    Thread.Sleep(2000);
    barrier.SignalAndWait();
    Console.WriteLine("End of sprint 1 (task2)");

    Console.WriteLine("Start of sprint 2 (task2)");
    Thread.Sleep(2000);
    barrier.SignalAndWait();
    Console.WriteLine("End of sprint 2 (task2)");   
}