如何使用多个变量在C#中锁定范围 [英] How to use Multiple Variables for a lock Scope in C#
问题描述
我在那里一个代码块应该只如果两个更衣室对象都是免费的执行情况。
I have a situation where a block of code should be executed only if two locker objects are free.
我希望有会是这样的:
lock(a,b)
{
// this scope is in critical region
}
不过,似乎没有这样的。所以,它的意思是这样做的唯一方法是:
However, there seems to be nothing like that. So does it mean the only way for doing this is:
lock(a)
{
lock(b)
{
// this scope is in critical region
}
}
请问这甚至达到预期效果?虽然代码编译,但我不知道它是否会达到什么样的,我就期待着。
Will this even work as expected? Although the code compiles, but I am not sure whether it would achieve what I am expecting it to.
推荐答案
我期望它,虽然会是它可能会导致死锁状态的情况。
I'd expect it to, though there'd be a case where it could potentially cause a deadlock condition.
通常情况下,代码会试图锁定 A
,然后进行锁定 b
如果成功了。这意味着,它只会执行代码,如果它可以同时锁定 A
和 B
。这是你想要的。
Normally, the code will attempt to lock a
and then proceed to lock b
if that succeeded. This means that it would only execute the code if it could lock both a
and b
. Which is what you want.
然而,如果一些其他的代码已经上了车 A锁B
那么这段代码不会做你期望的。你也想需要确保无处不在,你需要锁定两个 A
和 B
尝试获得锁以相同的顺序。如果你得到 B
,然后再 A
您会导致死锁。
However, if some other code has already got a lock on b
then this code will not do what you expect. You'd also need to ensure that everywhere you needed to lock on both a
and b
you attempt to get the locks in the same order. If you get b
first and then a
you would cause a deadlock.
这篇关于如何使用多个变量在C#中锁定范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!