4
votes

I'm developing on an old codebase which has following code in several places:

Mutex mutex = new Mutex(false, "<some mutex name>");
mutex.WaitOne();
try {
    // do something
} finally {
    mutex.ReleaseMutex();
}

Those mutexes are used for intra-process synchronization so I rewrote them using locks instead and the problems seem to be gone.

I am aware that the code is not the best one out there (compared to What is a good pattern for using a Global Mutex in C#?), but that doesn't explain to me why mutex.ReleaseMutex() occasionally throws "Mutex is not owned".

So I'm asking what is missing in (or wrong with) the code above, that produces the exception?

1
What is "// do something" actually doing? Could it be that it is releasing the mutex (in some cases).Christian.K
In some cases it is/was used when processing a List (searching, adding and removing elements), in other cases sending/receiving messages over TCP. It was also used for locking log4net calls like logger.Debug("message") (not really sure why as log4net should take care of the locking).Avo Muromägi
If that's really the code, then the ReleaseMutex call shouldn't ever throw that exception. Are you sure that nothing in the "do something" code releases the mutex? Is the code always calling WaitOne and not WaitOne(timeout)?Jim Mischel

1 Answers

3
votes

This usually means the thread attempting to release the mutex isn't the one that created it.

There is a good analysis of the problem here: http://blogs.msdn.com/b/willstan/archive/2009/03/03/the-attempt-to-release-mutex-not-owned-by-caller-exception-what-is-it-and-how-to-avoid-it.aspx