4

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?

wonea
  • 4,783
  • 17
  • 86
  • 139
Avo Muromägi
  • 1,563
  • 1
  • 12
  • 21
  • 2
    What is "// do something" actually doing? Could it be that it is releasing the mutex (in some cases). – Christian.K Nov 28 '11 at 09:31
  • 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 Nov 28 '11 at 09:52
  • 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 Dec 22 '11 at 00:13

1 Answers1

3

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

KingCronus
  • 4,509
  • 1
  • 24
  • 49