gpt4 book ai didi

multithreading - 释放互斥锁 : Object synchronization method was called from an unsynchronized block of code

转载 作者:行者123 更新时间:2023-12-04 17:34:29 25 4
gpt4 key购买 nike

我有这段非常简单的代码,它很少抛出“System.ApplicationException:对象同步方法是从未同步的代码块中调用的”。当释放互斥 () 叫做。

我从逻辑上分析了该方法的流程,只是无法理解这是如何/为什么会发生的。
据我了解,在这种情况下,互斥锁的所有权得到保证:

    readonly string mutexKey;

public Logger(string dbServer, string dbName)
{
this.mutexKey = ServiceManagerHelper.GetServiceName(dbServer, dbName);
}

private void Log(LogType type, string message, Exception ex)
{
using (var mutex = new Mutex(false, mutexKey))
{
bool acquiredMutex;
try
{
acquiredMutex = mutex.WaitOne(TimeSpan.FromSeconds(5));
}
catch (AbandonedMutexException)
{
acquiredMutex = true;
}

if (acquiredMutex)
{
try
{

// some application code here

}
finally
{
mutex.ReleaseMutex();
}
}
}
}

最佳答案

        catch (AbandonedMutexException)
{
acquiredMutex = true;
}

这是您代码中的一个非常严重的错误。捕获 AbandonedMutexException 永远不正确,它是 非常严重的事故。另一个线程获取了互斥体,但没有调用 ReleaseMutex() 就终止了。您已经无法恢复地失去同步,并且互斥锁不再可用。

您犯了一个错误并假设您无论如何都获得了互斥锁,这有点幸运。你没有。 ReleaseMutex() 调用现在将轰炸您引用的异常。

除了终止程序(明智的选择)或完全禁用日志记录以便永远不会再次使用互斥锁之外,您无法从这种不幸中恢复。通过删除 catch 子句做出明智的选择。发现问题的真正根源,即崩溃且未调用 ReleaseMutex() 的线程与此问题无关,没有任何提示。你一直忽略这个问题,通过抓AME来掩盖它,你不能忽略它。

关于multithreading - 释放互斥锁 : Object synchronization method was called from an unsynchronized block of code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27368179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com