How can I stop a thread in C#?

前端 未结 4 1573
逝去的感伤
逝去的感伤 2021-01-16 05:27

I\'ve created a Client-Server application, and on the Server I want to have the oportunity to stop the server and then start it again. The problem is that I can\'t stop the

4条回答
  •  星月不相逢
    2021-01-16 06:23

    In general, you should "stop" threads by indicating that you want them to stop, and letting them do it. It's recommended that you don't use Thread.Abort except for emergency situations where you're shutting down the whole application. (Calling Thread.Abort on the currently executing thread is safer, but still generally icky. That's what ASP.NET does when you redirect, by the way.)

    I have a page about stopping threads gracefully. You don't have to use that exact code, of course - but the pattern of setting a flag and testing it periodically is the main point.

    Now, how that gets applied in your particular situation will depend on how you're listening for TCP connections. If you could post the code used by that thread, we may be able to adapt it appropriately.

提交回复
热议问题