问题描述
|
我想-出于晦涩的原因,您不要质疑-在一个方法中开始一个锁,然后在另一个方法中结束。有点像:
object mutex = new object();
void Main(string[] args)
{
lock (mutex)
{
doThings();
}
}
具有与以下相同的行为:
object mutex = new object();
void Main(string[] args)
{
Foo();
doThings();
Bar();
}
void Foo()
{
startLock(mutex);
}
void Bar()
{
endlock(mutex);
}
问题是,当然,lock关键字以块语法运行。我知道锁并不是要像这样使用的,但是我对开放性的S / O解决方案不抱太大希望。 :)
解决方法
private readonly object syncRoot = new object();
void Main(string[] args)
{
Foo();
doThings();
Bar();
}
void Foo()
{
Monitor.Enter(syncRoot);
}
void Bar()
{
Monitor.Exit(syncRoot);
}
[编辑]
当您使用lock
时,.NET 4中发生的情况就是这样:
bool lockTaken = false;
try
{
Monitor.Enter(syncRoot,ref lockTaken);
// code inside of lock
}
finally
{
if (lockTaken)
Monitor.Exit(_myObject);
}