C# .Net 4.0 控制台应用程序 - 如何保持活动状态直到所有线程完成?
可能的重复:
C#:等待所有线程完成
我有一个控制台应用程序,产生一些线程然后退出。每个线程大约需要 20 秒才能完成。看起来控制台应用程序正在生成线程,然后在线程有机会完成之前退出。
如何告诉控制台应用程序在其生成的所有线程完成之前不要退出?
Possible Duplicate:
C#: Waiting for all threads to complete
I have a console app that spawns some threads and then exits. Each thread takes roughly ~20 seconds to complete. It appears as though the console app is spawning the threads and then exiting before the threads have a chance to complete.
How do I tell the console app not to exit until all threads it has spawned have completed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以使用
CountDownEvent
。You can to use a
CountDownEvent
.线程是否会循环生成?如果是这样,Parallel.ForEach 就可以工作:
Are the threads spawned for a loop? If so a Parallel.ForEach would work:
只要
Thread
不是后台线程 (.IsBackground
),应用程序就应该保持活动状态:不需要其他任何东西。请注意,
ThreadPool
将使用后台线程;问题可能是您在这里使用 ThreadPool 吗?注意:如果第二个线程实际上还没有启动,那么可能会发生一场小竞赛,它可能会提前退出;您可能想要对线程启动进行门控。
As long as the
Thread
is not a background-thread (.IsBackground
), the app should stay alive:Nothing else is needed. Note that the
ThreadPool
will use background threads; is the problem perhaps that you are usingThreadPool
here?Note: if the second thread hasn't actually started there might be a small race where it can exit prematurely; you might want to gate the threads starting.
您可以使用 Thread.Join 来等待线程完成。
You can use
Thread.Join
to wait for a thread to complete.你如何启动线程?这确实取决于,但如果您只是使用 Thread 类,则从主线程调用
yourThread[i].Join()
以确保所有线程完成。查看任务和任务工厂来处理事情比过去几年干净得多。
How are you launching the threads? It really depends, but if you are just using the Thread class, then call
yourThread[i].Join()
from the main thread to ensure that all threads complete.Look into the Tasks and Task Factory to handle things a lot more cleanly than in years past.
在启动后启动的所有线程上调用 Thread.Join() 。这将阻塞当前线程,直到线程完成。
Call
Thread.Join()
on all of the Threads that you start after they have started. This will block the current thread until the thread is complete.您可能应该使用同步并等待任何生成的线程完成其工作,方法是通过调用 Thread.Join 来阻止主线程或使用信号发送(例如使用监视器或其他选项之一)。
或者,您可以简单地通过设置 IsForeground 属性 (afaicr) 使生成的线程作为前台线程运行。这将使应用程序保持活动状态,直到线程终止,但您仍然会看到控制台窗口随着主线程退出而消失。
You should probably use synchronization and wait for any spawned threads to complete their work, either by blocking the main thread with calls to Thread.Join or using signalling (e.g. using a Monitor or one of the other options for this).
Alternatively you can simply make the spawned threads run as foreground threads, by setting the IsForeground property (afaicr). This will keep the application alive until the threads have terminated, but you will still see the console window disappear as the main thread exits.