c# - 从未同步的代码块调用了对象同步方法

标签 c# .net synchronization

我在以下代码中的 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/

相关文章:

java - Android游戏循环中的同步

c# - ConfigureAwait 并将异步调用与同步调用混合

c# - 显式事件添加/删除,误解了吗?

来自 rtsp ipcamera 的 FFmpeg 高效捕获

opengl - GLSL:关于连贯的限定词

javascript - .NET 正则表达式在客户端不起作用

c# - 如何使用预构建事件命令行将参数传递到 T4 模板

c# - LinkLabel...在默认网络浏览器中打开?

c# - 为通用参数指定构造函数约束

c# - TabControl 取消选项卡的更改