从未同步的代码块调用对象同步方法
我在生产中收到异常消息“对象同步方法是从不同步的代码块调用的”,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 的互斥体的保存进程。 我仍然不确定这种异常是如何发生的。
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();
}
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这段代码:
这不是线程安全的,可能会创建多个互斥锁。使用假装时间,让我们看一下这个例子:
希望这个插图不是垃圾。
如果您确实想对互斥体执行此操作,则使用 System.Lazy类是执行延迟初始化的线程安全方法。
鉴于此,您为什么要尝试延迟初始化互斥体?你如何处置它?
This code:
That is not thread safe, more than one Mutex may get created. Using pretend time, let's look at this example:
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.Given that, why are you trying to lazy initialize your Mutex? How are you disposing of it?