当线程池线程所有后台完成通知 [英] be notified when all background threadpool threads are finished

查看:166
本文介绍了当线程池线程所有后台完成通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,当我开始3..10线程与线程池。
每一个线程,它的工作并返回到线程池。
什么是当所有的后台线程已经完成主线程被通知可能的选择?

I have a scenario when I start 3..10 threads with ThreadPool. Each thread does its job and returns to the ThreadPool. What are possible options to be notified in main thread when all background threads have finished?

目前我使用的是自主研发的方法,递增一个变量为每创建线程和递减它,当后台线程即将完成。
这只是正常的,但我很好奇,如果有更好的选择。

Currently I'm using a homegrown method with incrementing a variable for each of created threads and decrementing it when a background thread is about to finish. This works just fine, but I was curious if there are better options.

推荐答案

递减的变量(线程之间)是有点冒险,除非有 Interlocked.Decrement 完成,但这种方法应该是罚款,如果你有最后一个线程(即当它到达零)引发事件。请注意,它必须是在一个finally块,以避免在例外的情况下,失去它(加上你不想杀进程)。

Decrementing a variable (between threads) is a little bit risky unless done with Interlocked.Decrement, but that approach should be fine if you have the last thread (i.e. when it gets to zero) raise an event. Note that it would have to be in a "finally" block to avoid losing it in the case of exceptions (plus you don't want to kill the process).

在并行扩展(或.NET 4.0),你也可以看看这里的 Parallel.ForEach 选项...这可能是让一切做的另一种方式块。无需手动看着他们。

In "Parallel Extensions" (or with .NET 4.0), you might also look at the Parallel.ForEach options here... that might be another way of getting everything done as a block. Without having to watch them all manually.

这篇关于当线程池线程所有后台完成通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆