C#等同于Objective-C的dispatch_group和队列?

时间:2014-11-08 23:17:03

标签: c# objective-c multithreading

我正在将Objective-C应用移植到C#,我正在努力在C#中实现以下功能

// create a new dispatch group
dispatch_group_t dispatchGroup = dispatch_group_create();

dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    // iterate over a collection adding blocks to the dispatchQueue identified by dispatchGroup
    dispatch_group_async(dispatchGroup, dispatchQueue, ^{
        // do stuff
    });
}

// wait for them all to finish
dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER);

// do more stuff that depends on them all finishing

我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

注意:这至少需要.NET Framework 4.5版。

// create a new dispatch group
List<Task> tasks = new List<Task>();

// iterate over a collection adding tasks to the dispatch group
for (…) {
    Task task = Task.Run(() => {
        // do stuff
    });
    tasks.Add(task);
}

// wait for them all to finish
Task.WaitAll(tasks.ToArray());

// do more stuff that depends on them all finishing