开发者

Force parameter evaluation for anonymous function

I wonder if there's easy way to force parameter evaluation for anonymous function? It is significant

for multithread programming. For example when i wrote

        for(int i=0; i<5; ++i)
        {
            Task.Factory.StartNew(() => Console.WriteLine(i));
        }

Most people would get "5" five times. In fact the cod开发者_JAVA百科e snip is more likely expected to ouput 0 to 5.

One quick solution is following:

        for(int i=0; i<5; ++i)
        {
            var local = i;
            Task.Factory.StartNew(() => Console.WriteLine(local));
        }

I think life is better if following method existed to evaluate all parameters for anonymous function and return one as same logic as the origin:

    Action EvaluateParameters(Action action)

Any ideas?

Thanks.


I don't know if such a method is even (reasonably) possible without compiler or framework support. In the end the compiler does generate code to hoist the variable, not it's value at the time you create the delegate, which leads to that behavior.

Basically, you would have to "execute" the delegate inside "EvaluteParameters" to get it working. Or maybe fiddling with Expressions could somehow do that.

BTW, this is only an issue if the delegate is created inside the loop but invoked outside (after) it.

Oh, and ReSharper does have a warning for that (even though it is sometimes "wrong" or overly pedantic).

Anyway, Jon Skeet does mention in his book (C# in Depth), that there is indeed some confusion about this in the community and that Microsoft is considering maybe changing the behavior in a future version (hopefully I got that somewhat right from memory). Which might not even be possible without breaking existing code that does depend on the current behavior (or works accidentally because of it).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜