从不同步的代码块调用对象同步方法

Myk*_*huk 1 .net c# 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

可能有多个进程可以使用具有不同和相同mutextName的互斥锁.而且我仍然不确定那个例外是如何发生的.

vcs*_*nes 7

这段代码:

Mutex Mutex
{
    get { return mutex ?? (mutex = new Mutex(false, mutexName)); }
}
Run Code Online (Sandbox Code Playgroud)

这不是线程安全的,可能会创建多个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!

希望这个插图不是垃圾.

System.Lazy<T>如果您真的想使用互斥锁,那么使用该类是一种线程安全的延迟初始化方法.

private Lazy<Mutex> _lazyMutex = new Lazy<Mutex>(() => new Mutex(false, "MyMutex"));
Mutex Mutex
{
    get { return _lazyMutex.Value; }
}
Run Code Online (Sandbox Code Playgroud)

鉴于此,你为什么要懒惰初始化你的Mutex?你是怎么处理它的?