Enumerators and locks.
-
Does anyone know how to best lock access to the object during enumeration? Eg, is it a bad/good idea to use a Monitor.Enter in the constructor and a Monitor.Exit in the dispose function? I know, I could put a lock around, but I really need this to happen automatically. Cheers.
-
Does anyone know how to best lock access to the object during enumeration? Eg, is it a bad/good idea to use a Monitor.Enter in the constructor and a Monitor.Exit in the dispose function? I know, I could put a lock around, but I really need this to happen automatically. Cheers.
-
Check out this [e-book]. It has some really nice examples on (automatic) locking and when (not) to use it in chapter 2. You might want to look at the Mutex class.
Standards are great! Everybody should have one!
-
Does anyone know how to best lock access to the object during enumeration? Eg, is it a bad/good idea to use a Monitor.Enter in the constructor and a Monitor.Exit in the dispose function? I know, I could put a lock around, but I really need this to happen automatically. Cheers.
When you compile this code:
IEnumerable<string> Test() {
lock (someObj) {
yield return "a";
yield return "b";
}
}Then the C# compiler creates an enumerator class that calls Monitor.Enter on the first MoveNext call; and calls Monitor.Exit in the third MoveNext call, or in the Dispose method if Dispose is called between after the first MoveNext call and before the third. foreach will automatically dispose the enumerator, but I've seen people write code like
IEnumerable<MyType> myCollection = ...;
if (e.GetEnumerator.MoveNext()) { // if the collection is not emptySo yes, using Monitor.Exit in the Dispose function is the way locking is meant to happen in enumerators, but make sure that your team is aware of the fact that enumerators must be disposed!