多线程-程序结束时的清理策略
以干净的方式完成多线程应用程序的最佳方法是什么?
我正在单独的套接字中从主线程启动多个套接字连接,并等到主线程中的工作日结束,然后使用当前的 System.Environment.Exit(0) 来终止它。
这会导致其中一个孩子出现未处理的异常。我应该停止列表中的线程吗?我一直不愿意对孩子们实施任何真正的停止,因此我想知道最佳做法。套接字都用适当的析构函数很好地包装起来,用于注销和关闭,但它仍然会导致错误。
What is the best way to finish a multi-threaded application in a clean way?
I am starting several socket connections from the main thread in seperate sockets and wait until the end of my business day in the main thread and use currently System.Environment.Exit(0)
to terminate it.
This leads to an unhandled exception in one of the childs. Should I stop the threads from the list? I have been reluctant to implement any real stopping in the childs yet, thus I am wondering about the best practice. The sockets are all wrapped nicely with proper destructors for logging out and closing, but it still leads to errors.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看看 jon skeet 关于多线程的文章:
http://www.yoda.arachsys.com /csharp/threads/
特别是“正常关闭工作线程”:
http://www.yoda.arachsys.com/csharp/threads/shutdown.shtml
have a look at jon skeet's articles about multithreading:
http://www.yoda.arachsys.com/csharp/threads/
especially "Shutting down worker threads gracefully":
http://www.yoda.arachsys.com/csharp/threads/shutdown.shtml
对于手动创建的线程,您应该设置 IsBackground属性为真。在这种情况下(如果除主线程之外的所有线程)都将处于后台,您的应用程序在从 Main(string[] arg) 函数返回后会正常关闭。
PS 所有线程池线程都是后台线程。
For manualy created threads you should set IsBackground property to true. In this case (if all your threads except main one) would be background, you application gracefully closed after returning from Main(string[] arg) function.
P.S. All Thread pools threads are background.
每当您执行长时间阻塞等待(例如等待传入连接)时,请使用该方法的 Begin/End 形式。然后使用 ManualResetEvent 来表示“应该退出”条件。然后阻止 AsyncWaitHandle 和退出事件。这将使您能够干净地终止。
示例:
当您想退出时,在您的 main 方法中:
Whenever you do a long blocked wait (such as waiting for an incoming connection) use the Begin/End form of the method. Then use a ManualResetEvent to represent the 'should exit' condition. Then block on the AsyncWaitHandle and the exit event. This will allow you to terminate cleanly.
Example:
And in your main method when you want to quit: