How to know if all the Thread Pool's thread are already done with its tasks?

萝らか妹 提交于 2019-12-03 13:33:18

Generally I would do something like this by having a counter variable. For each work item you queue in the ThreadPool add one to the counter variable. Then when it is processed you would decrease the counter variable.

Be sure that you do the incrementing and decrementing via the methods on the Interlocked class as this will ensure that things are done in a thread-safe manner.

Once the counter hits zero you could flag that the tasks are completed using a ManualResetEvent

If you have access to .NET 4 then you can use the new CountdownEvent class to do a similar thing.

1) How to know if all threads are finished?

You will have to let the Threads do their own check-in/check-out, by bracketing your code between:

Interlocked.Increment(ref jobCounter);
// your code
Interlocked.Decrement(ref jobCounter);

If this messes up your anonymous delegates too much then just use wrapper methods. You are probably going to have to add exception handling too.

The interlocked approach still eaves the problem of waiting for it to become 0, a loop with Sleep() is a weak but in this case viable solution.

2) You are starting threads in a recursive Tree walker. Be careful, you are probably creating too much of them and that will hurt performance.

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