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

后端 未结 7 1549
温柔的废话
温柔的废话 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 02:55

    The service control manager (SCM) will return when you return from OnStop. So you need to fix your OnStop implementation to block until all the threads have finished.

    The general approach is to have OnStop signal all your threads to stop, and then wait for them to stop. To avoid blocking indefinitely you can give the threads a time limit to stop, then abort them if they take too long.

    Here is what I've done in the past:

    1. Create a global bool flag called Stop, set to false when the service is started.
    2. When OnStop method is called, set the Stop flag to true then do a Thread.Join on all the outstanding worker threads.
    3. Each worker thread is responsible for checking the Stop flag, and exit cleanly when it is true. This check should be done frequently, and always before a long running operation, to avoid having it delay the service shutdown for too long.
    4. In the OnStop method, also have a timeout on the Join calls, to give the threads a limited time to exit cleanly... after which you just abort it.

    Note in #4 you should give adequate time for your threads to exit in normal case. Abort should only happen in unusual case where thread is hung... in that case doing an abort is no worse than if the user or system kills the process (the latter if the computer is shutting down).

提交回复
热议问题