views:

164

answers:

2

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!!

+1  A: 

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

Spencer Ruport
FYI the worker is a queue consumer that is running a random number of threads depending on configuration.
despart
A: 

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.

Steve Cooper