对象同步方法从code未同步块称为 [英] Object synchronization method was called from an unsynchronized block of code

查看:209
本文介绍了对象同步方法从code未同步块称为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到的产品与信息的异常上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?

这篇关于对象同步方法从code未同步块称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆