等待所有线程完成,不是所有的 [英] Wait for ANY thread to finish, not ALL
问题描述
我开始多个主题,想知道什么时候任何结束。我知道以下代码:
foreach(线程中的线程t)
t.Join
但它只会等待所有这太晚了。我需要知道什么时候一个线程完成,即使其他线程仍在运行。我正在寻找等效于 WaitAny
的东西只用于线程。但我不能添加代码到我正在监控的所有线程,所以使用信号或其他同步对象不是一个选项。
一些澄清: strong>我正在工作日志/跟踪工具,应该记录应用程序的活动。我可以在线程启动时插入日志语句,但是我不能在每个可能的线程外插入一个日志语句(多个出口点,异常等)。所以我想注册新的线程,然后通知它完成写一个日志条目。我可以异步加入
在每个线程,但这意味着每个监视线程的第二个线程,可能看起来有点开销。线程被各种手段使用,无论是 BackgroundWorker
,任务
或池线程。在它的本质,它是一个线程,我想知道什么时候完成。确切的线程机制由应用程序定义,而不是日志记录解决方案。
在我看来 WaitHandle .WaitAny
是最好的解决方案,因为你不喜欢使用它为某些xyz原因,你可以尝试这样的东西。
Thread.Join(int)方法的优点,它需要 millisecond timeout
并在线程终止时返回 true
,如果超时则返回 false
List< Thread> threads = new List< Thread>();
while(!threads.Any(x => x.Join(100)))
{
}
您可以更改加入
的超时。如果您知道需要多长时间。 / p>
I'm starting multiple threads and would like to know when any of then finishes. I know the following code:
foreach (Thread t in threads)
t.Join();
But it will only wait for all threads together. That's much too late. I need to know when one thread finishes, even when other threads are still running. I'm looking for something equivalent to WaitAny
only for threads. But I can't add code to all threads I'm monitoring, so using signals or other synchronisation objects is not an option.
Some clarification: I'm working on a logging/tracing tool that should log the application's activity. I can insert log statements when a thread starts, but I can't insert a log statement on every possible way out of the thread (multiple exit points, exceptions etc.). So I'd like to register the new thread and then be notified when it finishes to write a log entry. I could asynchronously Join
on every thread, but that means a second thread for every monitored thread which may seem a bit much overhead. Threads are used by various means, be it a BackgroundWorker
, Task
or pool thread. In its essence, it's a thread and I'd like to know when it's done. The exact thread mechanism is defined by the application, not the logging solution.
In my opinion WaitHandle.WaitAny
is the best solution, since you don't like to use it for some xyz reason you can try something like this.
Take the advantage of Thread.Join(int) method which takes millisecond timeout
and returns true
when thread is terminated or false
when timed out.
List<Thread> threads = new List<Thread>();
while (!threads.Any(x=> x.Join(100)))
{
}
You can alter the timeout of Join
If you know how long it will take.
这篇关于等待所有线程完成,不是所有的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!