How to properly stop a multi-threaded .NET windows service?

后端 未结 7 1519
温柔的废话
温柔的废话 2020-12-24 02:11

I have a windows service written in C# that creates a truck load of threads and makes many network connections (WMI, SNMP, simple TCP, http). When attempting to stop the win

相关标签:
7条回答
  • 2020-12-24 03:04

    The call to stop the service returns as soon as your OnStop() callback returns. Based on what you've shown, your OnStop() method doesn't do much, which explains why it returns so fast.

    There are a couple of ways to cause your service to exit.

    First, you can rework the OnStop() method to signal all the threads to close and wait for them to close before exiting. As @DSO suggested, you could use a global bool flag to do this (make sure to mark it as volatile). I generally use a ManualResetEvent, but either would work. Signal the threads to exit. Then join the threads with some kind of timeout period (I usually use 3000 milliseconds). If the threads still haven't exited by then, you can call the Abort() method to exit them. Generally, Abort() method is frowned upon, but given that your process is exiting anyway, it's not a big deal. If you consistently have a thread that has to be aborted, you can rework that thread to be more responsive to your shutdown signal.

    Second, mark your threads as background threads (see here for more details). It sounds like you are using the System.Threading.Thread class for threads, which are foreground threads by default. Doing this will make sure that the threads do not hold up the process from exiting. This will work fine if you are executing managed code only. If you have a thread that is waiting on unmanaged code, I'm not sure if setting the IsBackground property will still cause the thread to exit automatically on shutdown, i.e., you may still have rework your threading model to make this thread respond to your shutdown request.

    0 讨论(0)
提交回复
热议问题