Search code examples
c#dynamicreflectionreflection.emit

Reflection.Emit and Parallel.ForEach


I'm trying to write dynamic method that calls Parallel.ForEach. I have checked a IL of a sample class and I noticed that there's a nested type generated that's named <>c__DisplayClass#

I did manage to create a dynamic implementation of Parallel.ForEach but my nested class is of normal type. It is not named as <>c__....

And I think because of that my generated code looks a bit different when inspecting it in Reflector:

private void SayHello(string name)
{
    SayHelloInvoker invoker = new SayHelloInvoker(name);
    Parallel.ForEach<ITest>(this, new Action<ITest>(invoker.SayHello));
} 

But the compile code inspected in Reflector looks like:

private void SayHello(string name)
{
    Parallel.ForEach<ITest>(this, delegate (ITest x) { x.SayHello(name)); });
}

Current implementation works just fine but I would still like to figure out where's the catch in generating nested typed as <>c__....

So please if someone can point me in the right way so I can satisfy my curiosity. :)


Solution

  • When you make an anonymous method that uses variables from the parent method, the C# compiler generates a closure class named <>c_... to share those variables.

    For more information, see my blog post.

    If you generate a method dynamically, you can do whatever you want to ensure that the method has access to the variables it needs.
    In your case, your SayHelloInvoker is (presumably) serving the same role as the generated closure type, but with a more readable name, just like the GreaterThan class from my previous closure-less example.