我在以下代码中的 Mutex.ReleaseMutex() 上收到消息“从未同步的代码块调用对象同步方法”的异常消息:
Mutex Mutex
{
get { return mutex ?? (mutex = new Mutex(false, mutexName)); }
}
[NonSerialized]
Mutex mutex;
public void Log(/*...*/)
{
Mutex.WaitOne();
try
{
/*...*/
}
finally
{
Mutex.ReleaseMutex();
}
}
可能有一些进程可以使用具有不同和相同 mutextName 的互斥锁。 而且我仍然不确定该异常是如何发生的。
最佳答案
这段代码:
Mutex Mutex
{
get { return mutex ?? (mutex = new Mutex(false, mutexName)); }
}
这不是线程安全的,可能会创建多个 Mutex。使用假装时间,让我们看一下这个例子:
Thread A | Thread B ------------------------------------- Enters Is Null? (yes) Enters Create Mutex Is Null? (yes) <- Thread A hasn't assigned it yet. Assign mutex Create Mutex Use Mutex Assign mutex <- Oops! We just overwrote the mutex thread A created! Release Mutex <- Oops! We are trying to release the mutex Thread B created without owning it!
Hopefully that illustration isn't garbage.
Using the System.Lazy<T>
class is a thread-safe way of doing lazy initialization, if you really want to do that with your mutex.
private Lazy<Mutex> _lazyMutex = new Lazy<Mutex>(() => new Mutex(false, "MyMutex"));
Mutex Mutex
{
get { return _lazyMutex.Value; }
}
鉴于此,您为什么要尝试延迟初始化互斥量?你如何处理它?</p>
关于c# - 从未同步的代码块调用了对象同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7605077/