Controlled Parallel task execution what to use

末鹿安然 提交于 2019-12-24 20:52:52

问题


I'm running parallel tasks over some objects, to make this faster they run 4 in parallel. Now there is a new requirement, I need to perform a task that requires to be executed one at a time while the others must be waiting (the others cannot be performing another task).

I can't make the tests Sync.

Please check the image bellow as a better explanation.

Executing one at a time is done, but I thought of using a Semaphore to wait for the 4 objects in the beginning and at the end. The problem is that the Semaphore does not wait for all to complete in order to leave another to get in.

It must only start and leave this execution when all 4 have finished. What should I use for this?


回答1:


Use a Barrier object for this with a participation count of 4. Here's an example:

var barrier = new Barrier(4);

Then in your task method(s):

//do some work

//now, wait
barrier.SignalAndWait();

All methods will wait until all participants have called SignalAndWait() and then they will continue.



来源:https://stackoverflow.com/questions/49117255/controlled-parallel-task-execution-what-to-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!