简体   繁体   中英

Keeping a C# Mutex Alive in a Windows Service

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:

Mutex sessMutex = new Mutex(false, "sessMutex");
sessMutex.WaitOne();
// Write to the file ...... 
sessMutex.ReleaseMutex();
  1. Create the mutex - if the mutex already exists in the system, this will return the existing mutex!
  2. Try to lock
  3. Write to file
  4. Release lock

Apparently the service creates the mutex, locks it and start the file operations, then releases it, and then as soon as that method loses scope it's eligible for garbage collection. Subsequently, in the client, you seem to assume the mutex is still there.. yes storing it in the service scope may work, but then the client could still throw that exception if the service exited for whatever reason. your client will need to check if the mutex is still there. ps: then if it isn't, your service probably also isn't..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM