[Mono-list] yield

Jeroen Frijters jeroen at sumatra.nl
Fri Sep 23 03:01:46 EDT 2005


Miguel de Icaza wrote:
> > I wanted to use yield (like Miguel did it in 
> HttpApplication), but I need to 
> > lock by data. Is this not allowed?
> > 
> > static object lockit = new Object();
> > 
> > public static IEnumerable GetData()
> > {
> >   lock (lockit)
> >   {
> >    for (int i = 0; i < 10; i++)
> >     yield return true;
> >   }
> > }
> > 
> > I am getting this error (with Mono, it works with MS.Net):
> 
> This is a bug in the compiler.  But even with the bug fixed the code
> above will not work in the way you think it would.
> 
> The lock will be taken the first time, and released on the 
> first yield, and will not be taken again when the method resumes
> execution (although Monitor.Exit will be called repeated times).

This didn't look right to me, so I just looked at the code generated by
the August CTP and it certainly doesn't work like you describe. Instead
it does the "sensible" thing and acquires the lock when you first call
MoveNext() and releases the lock when the last MoveNext() returns false,
or when Dispose() is called.

> Basically yield and lock dont mix.

That's definitely true. Even though it "works", it's still a bad idea.

Regards,
Jeroen


More information about the Mono-list mailing list