Why doesn't Mutex get released when disposed?

后端 未结 9 1193
青春惊慌失措
青春惊慌失措 2020-11-29 02:22

I have the following code:

using (Mutex mut = new Mutex(false, MUTEX_NAME))
{
    if (mut.WaitOne(new TimeSpan(0, 0, 30)))
    {
       // Some code that dea         


        
9条回答
  •  不知归路
    2020-11-29 02:54

    Ok, posting an answer to my own question. From what I can tell, this is the ideal way to implement a Mutex that:

    1. Always gets Disposed
    2. Gets Released iff WaitOne was successful.
    3. Will not get abandoned if any code throws an exception.

    Hopefully this helps someone out!

    using (Mutex mut = new Mutex(false, MUTEX_NAME))
    {
        if (mut.WaitOne(new TimeSpan(0, 0, 30)))
        {
            try
            {
               // Some code that deals with a specific TCP port
               // Don't want this to run twice in multiple processes        
            }
            catch(Exception)
            {
               // Handle exceptions and clean up state
            }
            finally
            {
                mut.ReleaseMutex();
            }
        }
    }
    

    Update: Some may argue that if the code within the try block puts your resource in an unstable state, you should not release the Mutex and instead let it get abandoned. In other words, just call mut.ReleaseMutex(); when the code finishes successfully, and not put it within the finally block. The code acquiring the Mutex could then catch this exception and do the right thing.

    In my situation, I'm not really changing any state. I'm temporarily using a TCP port and can't have another instance of the program run at the same time. For this reason, I think my solution above is fine but yours may be different.

提交回复
热议问题