Thanks for the quick response.
I am writing a new Windows Service, based on one I made previously, but
since debugging Windows Services is somewhat of a pain, I moved all the code
to a Windows Forms application for the time being. Now I want to move
everything back to the Windows Service.
Since a Windows Forms application does not know about OnStart() and
OnStop(), I have create 2 buttons to 'simulate' the service's start and stop
The 'Service' use a lot of unmanaged threads etc. Therefore, I created a
class I call a 'Dispatcher' that keeps track of all threads etc. In the
service's OnStop() event, I will eventually call 'Dispatcher.Stop()'. The
Dispatcher then enters a stopping state; it will finish working threads, but
not create new ones. I have to wait for all current threads to finish.
There is a callback function I use. If the Dispatcher is finished
processing, it will trigger the callback function.
So, in the services OnStop() event, after the Dispatcher.Stop() call, I have
to wait for the callback to arrive OR for the Dispatcher to enter a Stopped
state. (Both are primarily the same.)
How can I wait for the Dispatcher to enter the stopped state? I cannot
return from the OnStop() method before all threads are really finished.
This is the code in the OnStop() method in the Windows Forms application;
protected override void OnStop()
_Stopping = true;
HandleEvent("Service is stopping.",
while (Dispatcher.State != DispatcherState.Stopped)
HandleEvent("Service stopped successfully.",
This is the code for the Dispatcher Callback in the Windows Forms
private void DispatcherDone_Callback()
HandleEvent("Dispatcher stopped unexpectedly.",
Any ideas how to wait for the dispatcher to stop in a Windows Serivce? Can I
use something like Thread.Sleep(1000)? Not too nice, but it might work. It
will lock up the Windows Forms application though....