锁的范围是什么?

时间:2015-01-20 08:25:06

标签: c# locking

我已经看到了这段代码from one of the jetbrain's team

查看此代码:

object myLock = new object()

public IEnumerable<int> Values()
{
 lock (myLock)
 {
   for (var i=0;i<10;i++)
     yield return i;
 }
}



public void Test()
{
 foreach (var value  in Values())
  {
    DoHugeJob(value);   
  }
}


void Main()
{
    Test();
}

问题:

lock的范围是什么?

1 个答案:

答案 0 :(得分:6)

如果您的意思是时间 - 首次调用MoveNext()时将获取锁定,并且在第11次调用MoveNext()时将释放 处理迭代器时的时间(即循环完成时)

例如:

var iterable = Values();
// Lock is *not* acquired yet...

foreach (var item in iterable.Take(5)) {
    // Lock has been acquired
}
// Lock has been released even though we didn't get to the
// end of the loop, because foreach calls Dispose

一般情况下,锁定迭代器块是一个坏主意,因为这样做 - 你真的想锁定一个简短易懂的程序期。