How to make a Win Service run Long Term with Threading

ε祈祈猫儿з 提交于 2019-12-04 12:40:27

First, for a long-running thread, create your own Thread object and start it; don't use the ThreadPool. The thread pool is designed for small, relatively short-lived operations.

Second, there are several ways that you can keep your thread alive. The most basic is what you've tried, which is a while loop with a sleep (or other blocking) call at the end. This is the most basic, though not necessarily the "best". There are other options, like named WaitHandle objects that can be accessed from other applications, that can allow for more deterministic code execution and fewer iterations of wake-check-sleep.

If, however, you either can't (or don't want to) modify the other processes to support notifying your service of particular events, then what you have is, essentially, correct. I would, however, encourage selecting a more reasonable Sleep time; do you really need to check every millisecond?

I solved that problem with my very long running Windows service by having OnStart() launch a System.Timers.Timer, and do all of the processing in the timer's ElapsedEventHandler.

Inside the handler I stop the timer, do the work on separate threads, check for a halt signal, and then restart the timer if it's OK to continue. The service's OnStop() method stops the timer and kills any active worker threads.

The worker threads handle all exceptions, so if one has a problem, it logs the exception, terminates, and then gets restarted on the next timer interval. The service core has never crashed.

In regards to your blocking, you should probably use a Wait/Pulse Programming paradigm for signalling one thread to continue. Or to just Join the thread.

Wait & Pulse - Threading in C#

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!