Enumerator/locks/yield

S

stuart_faircloth

I have the following class:

public class Class1 : IEnumerable<int>
{
List<int> values = new List<int>();

public IEnumerator<int> GetEnumerator()
{
lock(this) {
foreach (int i in values) {
yield return i;
}
}
}

If i iterate over an instance of class1 using the foreach operator how
will the instance of Class1 be locked (see lock inside
Class1.GetEnumerator). Is the lock just acquired once when the
GetEnumerator is first invoked? Is it acquired and released each time
the CLR calls the GetNext() on the generated Enumerator? or is the
lock acquired for the whole of the foreach and then released at the
end?

Thanks
 
J

Jon Skeet [C# MVP]

I have the following class:

public class Class1 : IEnumerable<int>
{
List<int> values = new List<int>();

public IEnumerator<int> GetEnumerator()
{
lock(this) {
foreach (int i in values) {
yield return i;
}
}
}

If i iterate over an instance of class1 using the foreach operator how
will the instance of Class1 be locked (see lock inside
Class1.GetEnumerator). Is the lock just acquired once when the
GetEnumerator is first invoked? Is it acquired and released each time
the CLR calls the GetNext() on the generated Enumerator? or is the
lock acquired for the whole of the foreach and then released at the
end?

The lock is acquired for the whole of whatever is iterating over your
instance. Note that if the caller doesn't use foreach, but explicitly
calls GetEnumerator() and MoveNext() etc, but gives up before the end
and forgets to call Dispose, you could end up failing to ever release
the lock.

Basically, I'd avoid doing this if you can.

(Locking on "this" is generally not a great idea anyway, btw.)
 
S

stuart_faircloth

Thelockis acquired for the whole of whatever is iterating over your
instance. Note that if the caller doesn't use foreach, but explicitly
calls GetEnumerator() and MoveNext() etc, but gives up before the end
and forgets to call Dispose, you could end up failing to ever release
thelock.

Basically, I'd avoid doing this if you can.

(Locking on "this" is generally not a great idea anyway, btw.)

--
Jon Skeet - <[email protected]>http://www.pobox.com/~skeet  Blog:http://www.msmvps.com/jon.skeet
World class .NET training in the UK:http://iterativetraining.co.uk- Hide quoted text -

- Show quoted text -

I found the following on an msdn website:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=785249&SiteID=1

Which is correct?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top