Search code examples
c#.netbackgroundworkeranonymous-methodsyield-return

How to yield return inside anonymous methods?


Basically I have an anonymous method that I use for my BackgroundWorker:

worker.DoWork += ( sender, e ) =>
{
    foreach ( var effect in GlobalGraph.Effects )
    {
        // Returns EffectResult
        yield return image.Apply (effect);
    }
};

When I do this the compiler tells me:

"The yield statement cannot be used inside an anonymous method or lambda expression"

So in this case, what's the most elegant way to do this? Btw this DoWork method is inside a static method, in case that matters for the solution.


Solution

  • Ok so I did something like this which does what I wanted (some variables omitted):

    public static void Run ( Action<float, EffectResult> action )
    {
        worker.DoWork += ( sender, e ) =>
        {
            foreach ( var effect in GlobalGraph.Effects )
            {
                var result = image.Apply (effect);
    
                action (100 * ( index / count ), result );
            }
        }
    };
    

    and then in the call site:

    GlobalGraph.Run ( ( p, r ) =>
        {
            this.Progress = p;
            this.EffectResults.Add ( r );
        } );