Reputation: 11780
I have a service that I would like it to become single instance, because when i click restart on services.msc, the new instance of the service starts when the old instance still haven't finished (because it has to perform some actions).
The code that finishes the service looks like this:
protected override void OnStop()
{
Log.Info("STOPPING SERVICE");
//Wait working threads to finish
_Worker.Die();
//Kill inner processes still running (sometimes some processes hang up and is the only way to kill them...
ProcessUtility.KillTree(System.Diagnostics.Process.GetCurrentProcess().Id);
//Call parent's class Stop
base.OnStop();
}
The class is a subclass of ServiceBase.
How can I make the new instance to only start when the old one has finished?
thx stackpowerflowers!!
Upvotes: 0
Views: 1559
Reputation: 21480
Have a look at the Mutex class. This lets you create a lock-like synchronization primitive that works across processes.
Try this constructor which takes a name; create a mutex called, say, "MYSERVICENAME" on OnStart; release it on OnStop. OnStart of the later service won't continue past the mutex until OnStop of the earlier service releases it.
Upvotes: 0
Reputation: 35117
By the way, I don't know what type Worker is but typically when you're waiting for a thread to terminate the call is join()
. You may want to check that the main thread is actually waiting for the worker thread to terminate.
Two issues, first, you should figure out why your service isn't terminating properly. Once you figure that out you can keep any additional instances from running by using a Mutex. The implementation is explained here, an article I found on Google, it even references Jon Skeet. That guy is everywhere!
http://www.ai.uga.edu/~mc/SingleInstance.html
Upvotes: 1