锁的范围是什么?

What is the scope of the lock?

我看过这段代码 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的范围是什么?

如果你的意思是时间 - 首次调用 MoveNext() 时将获取锁,并在 MoveNext() 调用时 either 释放锁第 11 次被调用(即当循环完成时) 当迭代器被释放时。

例如:

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

通常正因为如此,在迭代器块中锁定是个坏主意 - 您确实希望在程序的一个简短、易于理解的时间段内锁定。