ReleaseMutex : Object synchronization method was called from an unsynchronized block of code ReleaseMutex : Object synchronization method was called from an unsynchronized block of code multithreading multithreading

ReleaseMutex : Object synchronization method was called from an unsynchronized block of code


        catch (AbandonedMutexException)        {            acquiredMutex = true;        }

This is a very serious bug in your code. Catching an AbandonedMutexException is never correct, it is a very serious mishap. Another thread acquired the mutex but terminated without calling ReleaseMutex(). You've irrecoverably lost synchronization and the mutex is no longer usable.

You were sort of lucky by making a mistake and assuming that you acquired the mutex anyway. You didn't. The ReleaseMutex() call will now bomb with the exception you quoted.

You cannot recover from this mishap, other than by terminating the program (the wise choice) or by disabling logging completely so the mutex will never be used again. Make the wise choice by removing the catch clause. Discovering the true source of the problem, that thread that crashed and didn't call ReleaseMutex(), is out of context for this question, there are no hints. You've been ignoring this problem, papered it over by catching AME, you can't ignore it.


This exception is raised when you call ReleaseMutex() from a thread that does not own the mutex. Search // some application code here for code that releases the mutex.

Also reconsider whether you're actually calling ReleaseMutex() from the same thread where you called WaitOne(). Example: I arrived at this post because I was using async/await and my code resumed on a different thread and tried to release a mutex the thread didn't own.


In my case, i see the same behavior like Nathan Schubkegel. I use await's, and Thread.CurrentThread.ManagedThreadId gives another value for the "same" thread. I mean, thread was started with ManagedThreadId == 10, and Mutex was owned with this thread id, but later ReleaseMutex() causes ApplicationException with message: "Object synchronization method was called from an unsynchronized block of code", and i see that ManagedThreadId == 11 at this time :) . It seems, await sometimes changes thread id when returns. It seems, that is the reason. Mutex thinks that another thread wants to release it. It's sad, that Mutex documentation does not make ATTENTION on this moment.

So, you CAN NOT use asynchronous operator await between Mutex acquire and release. It's because C# compiler replaces plain operator await by asynchronous callback, and this callback can be made by ANOTHER thread. Usually, it's the same thread, but sometimes it's another thread (from thread pool).

Mutex checks thread. Only thread that acquired Mutex may release it. If you need synchronization without this checking, use Semaphore. SemaphoreSlim has asynchronous method WaitAsync() - it's cool.