对象同步方法从code未同步块称为对象、方法、code

由网友(一半爱情一半泪水)分享简介:我收到的产品与信息的异常上Mutex.ReleaseMutex()在以下code的对象同步方法从code不同步的块被称为:I receive an exception in production with message "Object synchronization method was called from a...

我收到的产品与信息的异常上Mutex.ReleaseMutex()在以下code的对象同步方法从code不同步的块被称为:

I receive an exception in production with message "Object synchronization method was called from an unsynchronized block of code" on Mutex.ReleaseMutex() in following code:

Mutex Mutex
{
    get { return mutex ?? (mutex = new Mutex(false, mutexName)); }
}
[NonSerialized]
Mutex mutex;

public void Log(/*...*/)
{
    Mutex.WaitOne();
    try
    {
        /*...*/
    }
    finally
    {
        Mutex.ReleaseMutex();
    }
}

有可能是saveral过程可以使用互斥不同和相同的mutextName。 而且还是我不知道该异常是如何发生的事。

There may be saveral processes which can use mutexes with different and same mutextName. And still I am not sure how that exception can happen there.

推荐答案

这code:

Mutex Mutex
{
    get { return mutex ?? (mutex = new Mutex(false, mutexName)); }
}

这是不是线程安全的,超过一个互斥体可能会产生。使用pretend时间,让我们来看看下面这个例子:

That is not thread safe, more than one Mutex may get created. Using pretend time, let's look at this example:


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.

使用 System.Lazy&LT; T&GT; 类是做延迟初始化的线程安全的方法,如果你真的想这样做,以你的互斥量

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; }
}

鉴于这种情况,为什么你想偷懒的初始化互斥?你是如何处理的呢?

Given that, why are you trying to lazy initialize your Mutex? How are you disposing of it?

阅读全文

相关推荐

最新文章