多线程-程序结束时的清理策略

发布于 2024-08-25 10:27:49 字数 224 浏览 1 评论 0原文

以干净的方式完成多线程应用程序的最佳方法是什么?
我正在单独的套接字中从主线程启动多个套接字连接,并等到主线程中的工作日结束,然后使用当前的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

幸福还没到 2024-09-01 10:27:49

看看 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

柠檬色的秋千 2024-09-01 10:27:49

对于手动创建的线程,您应该设置 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.

黎歌 2024-09-01 10:27:49

每当您执行长时间阻塞等待(例如等待传入连接)时,请使用该方法的 Begin/End 形式。然后使用 ManualResetEvent 来表示“应该退出”条件。然后阻止 AsyncWaitHandle 和退出事件。这将使您能够干净地终止。

示例:

// exit is a ManualResetEvent
var asyncResult = socket.BeginAccept(null, null);
if(WaitHandle.WaitAny(new[] { exit, asyncResult.AsyncWaitHandle }) == 0)
   return;
var connection = socket.EndAccept(asyncResult);

当您想退出时,在您的 main 方法中:

exit.Set();

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:

// exit is a ManualResetEvent
var asyncResult = socket.BeginAccept(null, null);
if(WaitHandle.WaitAny(new[] { exit, asyncResult.AsyncWaitHandle }) == 0)
   return;
var connection = socket.EndAccept(asyncResult);

And in your main method when you want to quit:

exit.Set();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文