- 1 year ago
How to implement mutex in windows service
To implement a mutex (mutual exclusion) in a Windows service using C#, you can use the Mutex
class from the System.Threading
namespace. Here's an example of how you can use a mutex in a Windows service:
csharpusing System;
using System.ServiceProcess;
using System.Threading;
namespace YourNamespace
{
public class YourService : ServiceBase
{
private Mutex mutex;
protected override void OnStart(string[] args)
{
// Create a named mutex
mutex = new Mutex(false, "YourServiceMutex");
// Check if another instance of the service is already running
if (!mutex.WaitOne(TimeSpan.Zero, false))
{
// Another instance is already running, so exit
this.Stop();
return;
}
// Continue with service startup
// ...
}
protected override void OnStop()
{
// Release the mutex when the service stops
mutex.ReleaseMutex();
mutex.Dispose();
// Perform cleanup and stop any ongoing operations
// ...
}
// Other methods and logic for your service
// ...
}
}
In the code above, we create a named mutex using new Mutex(false, "YourServiceMutex")
, where "YourServiceMutex"
is the name of the mutex. This allows different instances of the service to synchronize access to a shared resource.
In the OnStart
method, we check if another instance of the service is already running by calling mutex.WaitOne(TimeSpan.Zero, false)
. If the mutex is not available (indicating another instance is already running), we stop the current service instance and return.
If the mutex is available, we can proceed with the normal startup logic for the service. When the service stops (OnStop
method), we release the mutex using mutex.ReleaseMutex()
and dispose of the mutex object.
Make sure to adjust the code according to your specific service implementation. Run the service using the appropriate service management tools or through the command line to observe the mutex behavior.