sách gpt4 ăn đã đi

c# - Monitor.TryEnter/Monitor.Exit 和 SynchronizationLockException

In lại 作者:太空狗 更新时间:2023-10-29 23:59:02 27 4
mua khóa gpt4 giày nike

是否可以检测是否是同一个线程试图释放锁?我们在代码中有很多地方看起来像:

thử
{
thử
{
if(!Monitor.TryEnter(obj, 2000))
{
throw new Exception("can not lock");
}
}
Cuối cùng
{
Monitor.Exit(obj);
}
}
nắm lấy
{
//Log
}

上面的代码非常简化,实际上Enter 和Exit 语句位于自定义对象(锁管理器)中。

问题是,在该结构中,我们在尝试“退出”时遇到了 SynchronizationLockException,因为它看起来像是未成功锁定的线程,最终尝试释放。

所以问题是,我如何知道执行 Monitor.Exit 的线程是否与执行 Monitor.Enter 的线程相同?
我以为我可以使用 CurrentThread.Id 来同步进入和退出,但我不确定它是否足够“安全”。

câu trả lời hay nhất

So the question, is how I can know if the thread who making Monitor.Exit is the same thread who did Monitor.Enter?

据我所知,你不能,很容易。您无法找出哪个线程拥有监视器。

但是,这只是一个mã hóa问题 - 您应该更改您的代码,使其甚至不会thử释放不应该释放的监视器。所以你上面的代码可以重写为:

if (!Monitor.TryEnter(obj, 2000))
{
throw new Exception(...);
}
thử
{
// Presumably other code
}
Cuối cùng
{
Monitor.Exit(obj);
}

或者更好的是,如果您使用的是 .NET 4,请使用 overload of TryEnter它接受一个 Phải tham số:

bool gotMonitor = false;
thử
{
Monitor.TryEnter(obj, ref gotMonitor);
if (!gotMonitor)
{
throw new Exception(...);
}
// Presumably other code
}
Cuối cùng
{
if (gotMonitor)
{
Monitor.Exit(obj);
}
}

关于c# - Monitor.TryEnter/Monitor.Exit 和 SynchronizationLockException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14089640/

27 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress