我有这样一段非常简单的代码,很少会在调用ReleaseMutex()时抛出"System.ApplicationException: Object synchronization method was called from an unsynchronized block of code."。
我逻辑分析了该方法的流程,但无法理解为什么会发生这种情况。据我理解,这种情况下互斥锁的所有权是保证的:
readonly string mutexKey;
public Logger(string dbServer, string dbName)
{
this.mutexKey = ServiceManagerHelper.GetServiceName(dbServer, dbName);
}
private void Log(LogType type, string message, Exception ex)
{
using (var mutex = new Mutex(false, mutexKey))
{
bool acquiredMutex;
try
{
acquiredMutex = mutex.WaitOne(TimeSpan.FromSeconds(5));
}
catch (AbandonedMutexException)
{
acquiredMutex = true;
}
if (acquiredMutex)
{
try
{
// some application code here
}
finally
{
mutex.ReleaseMutex();
}
}
}
}