多个异步工作者,按顺序返回工作

时间:2013-06-01 00:19:53

标签: c# asynchronous worker

我正在尝试做什么:

将MasterQueue中的单个队列发送给他们自己的异步工作者

等待所有异步工作者完成并返回结果

订单的结果与MasterQueue中的顺序相同

<Queue<Queue<object[]>> MasterQueue = new Queue<Queue<object[]>>();

while (MasterQueue.Count > 0)
{

 Queue<object[]> Queue = MasterQueue.Dequeue();

 //Send Queue to an Async Worker for processing...
 //Lets say 5 in total that finish randomly so 3, 2, 5, 4, 1

}

//Wait for all 5 Async workers to finish and return their work, then use the work in original order...

//Use work from 1
//Use work from 2
//Use work from 3
//Use work from 4
//Use work from 5

1 个答案:

答案 0 :(得分:0)

创建一个任务数组(每个异步工作一个任务)并对任务使用Task.WaitAll(任务)。任务的顺序与列表/数组的顺序相同。

类似的东西:

while (masterQueue.Count > 0)
{
    Queue<object[]> queue = masterQueue.Dequeue();

    //Send Queue to an async Worker for processing...
    tasks.Add(Process(queue));
}

// tasks are already in order
Task.WaitAll(tasks.ToArray());

...
async static Task Process(Queue<object[]> queue)
{
    await Task.Factory.StartNew(() => { });
}