I have implemented a Windows Service in .NET 4 and C# using Visual Studio 2015. In the OnStart
method, my service creates a "Worker Thread" which loops, blocking on an AutoResetEvent
(connected to a Timer
). The "Worker Thread" also has a CancellationTokenSource
that it manually polls to check whether it should stop working. The OnStop
method first Cancels with the CancellationTokenSource and then signals with the AutoResetEvent, waking up the Worker thread which notices that "cancel" has happened, and which then exits.
This Windows Service works fine on Win7. I've installed it on Win10 a few times and it worked fine - until yesterday where I saw a logfile which said the Worker Thread had, as expected, blocked on the AutoResetEvent, but: that worker Thread never got to the next statement in my program. It never woke up, didn't execute another statement. 94 seconds after it blocked, the service ended.
Note that in this scenario my OnStop
method was not called.
The process as a whole had not been killed - there's a thread which comes in (threadID 1) presumably from the SCM or the OS, and which blocks until my service dies - that thread logged a few messages on the way out.
Here's my question: are there conditions where the Windows Service Control Manager (SCM) feels it necessary to actually kill off application threads? Can anyone explain why my thread died?
I discovered that restarting the machine caused my thread to die (interesting that the Windows-allocated thread didn't die, it just exited - I guess that's how the SCM cleans up services when it is told to shut down).
I didn't realize that I was barking up the wrong tree. My client app was saying the service was unavailable and I assumed it was because of what I described above - because it was getting killed off.
Not the problem - the problem was that once the service was stopped (because of shutdown), it was not getting restarted again!
So why didn't my .NET 4 Automatic
service get automatically started, in Win10? That's a different question.
I have since posting my original question, found several postings that answer the new question:
Automatic Services not starting on Win10 upgrade machine
So the diagnosis was that Win10 was doing some kind of combination of slowing down the startup of my .NET 4 service, and then punishing the service for its slow startup by killing it before it can start executing my code.
I did find System Event log entries that support this.
The solution for me turned out to be changing my "start type" from "Automatic" to "Automatic (Delayed)".
Some relevant links for me:
I hope all this helps someone else out there.