I’ve written a C# Windows Service application that reads a file via a timer delegate every 20 minutes or so, deserializes the content, and then clears the file. The file is written to by one or more client applications running on the same machine and I have chosen to use a Mutex to more or less “lock” the file while it is being deserialized and written to by the service.
I am doing this to avoid Exceptions in the rare occurrence that the client application and the service try to write to the file at the same time.
I create the Mutex inside of the Windows service via the following C# code (this is run every 20 minutes):
public void MyServiceFunction() {
Mutex sessMutex = new Mutex(false, "sessMutex");
sessMutex.WaitOne();
// Write to the file ......
sessMutex.ReleaseMutex();
}
In the client application I run the following:
public void MyClientFunction() {
Mutex mutex = Mutex.OpenExisting("sessMutex");
mutex.WaitOne();
// Write to the file ......
mutex.ReleaseMutex();
}
Now, if I start the Windows service and run the client application within a few minutes, everything works fine. However, after a few hours when attempting to execute the client application I get the following error:
No handle of the given name exists.
My question is, how do I prevent this error from occurring and “persisting” the Mutex.
Would storing the Mutex as property of the Windows service class work? Is using a Mutex the proper way to achieve the functionality I am looking for?
Thanks in advance for your help!
I don’t understand why you treat the mutex differently in your client.
It should be the same code in both programs: