gpt4 book ai didi

c# - C# 锁定将等待多长时间,如果代码在锁定期间崩溃怎么办?

转载 作者:IT王子 更新时间:2023-10-29 03:52:15 26 4
gpt4 key购买 nike

我看到了下面的代码,想用它做一个简单的activity,一次只能执行一个,不会频繁出现(所以一次出现两次的几率很小,但是你永远不知道)。

所以代码:

// class variable
private static object syncRoot = new object();

// in a method:
lock (syncRoot)
{
DoIt();
}

当另一个线程过来要执行代码时,它要等多久才能释放锁?永远,或者你能以某种方式设置超时吗?

其次:如果 DoIt() 方法抛出异常,锁是否仍然释放?

最佳答案

When another thread comes by and wants to execute the code, how long will it wait until the lock is released?

lock 将无限期地阻止试图进入锁的线程,直到被锁定的对象被释放。

can you somehow set a timeout?

如果需要指定超时,请使用 Monitor.TryEnter

if(Monitor.TryEnter(obj, new TimeSpan(0, 0, 1))) {
try {
body
}
finally {
Monitor.Exit(obj);
}
}

if the DoIt() method throws an exception, is the lock still released?

是的,一个 lock(obj) { body } 被翻译成:

bool lockWasTaken = false;
var temp = obj;
try { Monitor.Enter(temp, ref lockWasTaken); { body } }
finally { if (lockWasTaken) Monitor.Exit(temp); }

有关抛出异常时会发生什么的详细信息,请参阅 Locks and exceptions do not mix .

关于c# - C# 锁定将等待多长时间,如果代码在锁定期间崩溃怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6049346/

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