Avo Muromägi
Avo Muromägi

Reputation: 1593

Why do I get "Mutex is not owned" exception

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?

Upvotes: 4

Views: 5217

Answers (1)

KingCronus
KingCronus

Reputation: 4519

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

Upvotes: 3

Related Questions