【发布时间】:2015-02-06 17:02:01
【问题描述】:
我有这段非常简单的代码,它很少抛出“System.ApplicationException:对象同步方法是从未同步的代码块中调用的”。当 ReleaseMutex() 被调用时。
我从逻辑上分析了方法的流程,但无法理解这是如何/为什么会发生的。 据我了解,在这种情况下,互斥锁的所有权得到了保证:
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();
}
}
}
}
【问题讨论】:
标签: multithreading thread-safety mutex thread-synchronization