Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent multiple instance of a service - best approach?

Tags:

So what do you think is the best way to prevent multiple threads of a C# Windows service running simultaneously (the service is using a timer with the OnElapsed event) ?

Using lock() or mutex ?

I can't seem to grasp the concept of the mutex, but using lock() seems to work fine for my case.

Should I spend the time learning how to use the mutex anyways?

like image 265
Francis Ducharme Avatar asked May 04 '12 01:05

Francis Ducharme


People also ask

How do I create multiple instances of Windows service?

In order to add additional instance of a service to the Windows Service dialog box, each service must have a unique name. In order to achieve this you will need to use the Windows SC utility. The SC utility communicates with the Service Controller and installed services.


1 Answers

Make your timer a one-shot, and re-initialize it in the elapsed event handler. For example, if you're using System.Timers.Timer, you'd initialize it like this:

myTimer.Elapsed = timer1Elapsed; myTimer.Interval = 1000; // every second myTimer.AutoReset = false; // makes it fire only once myTimer.Enabled = true; 

And your elapsed event handler:

void timerElapsed(object source, ElapsedEventArgs e) {     // do whatever needs to be done     myTimer.Start(); // re-enables the timer } 

The drawback to this is that the timer doesn't fire on one second intervals. Rather, it fires one second after the last tick's processing finishes.

like image 120
Jim Mischel Avatar answered Sep 22 '22 03:09

Jim Mischel