Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture the value of an outer variable inside a lambda expression?

I just encountered the following behavior:

for (var i = 0; i < 50; ++i) {
    Task.Factory.StartNew(() => {
        Debug.Print("Error: " + i.ToString());
    });
}

Will result in a series of "Error: x", where most of the x are equal to 50.

Similarly:

var a = "Before";
var task = new Task(() => Debug.Print("Using value: " + a));
a = "After";
task.Start();

Will result in "Using value: After".

This clearly means that the concatenation in the lambda expression does not occur immediately. How is it possible to use a copy of the outer variable in the lambda expression, at the time the expression is declared? The following will not work better (which is not necessarily incoherent, I admit):

var a = "Before";
var task = new Task(() => {
    var a2 = a;
    Debug.Print("Using value: " + a2);
});
a = "After";
task.Start();
like image 656
Erwin Mayer Avatar asked Jun 15 '12 10:06

Erwin Mayer


2 Answers

This has more to do with lambdas than threading. A lambda captures the reference to a variable, not the variable's value. This means that when you try to use i in your code, its value will be whatever was stored in i last.

To avoid this, you should copy the variable's value to a local variable when the lambda starts. The problem is, starting a task has overhead and the first copy may be executed only after the loop finishes. The following code will also fail

for (var i = 0; i < 50; ++i) {
    Task.Factory.StartNew(() => {
        var i1=i;
        Debug.Print("Error: " + i1.ToString());
    });
}

As James Manning noted, you can add a variable local to the loop and copy the loop variable there. This way you are creating 50 different variables to hold the value of the loop variable, but at least you get the expected result. The problem is, you do get a lot of additional allocations.

for (var i = 0; i < 50; ++i) {
    var i1=i;
    Task.Factory.StartNew(() => {
        Debug.Print("Error: " + i1.ToString());
    });
}

The best solution is to pass the loop parameter as a state parameter:

for (var i = 0; i < 50; ++i) {
    Task.Factory.StartNew(o => {
        var i1=(int)o;
        Debug.Print("Error: " + i1.ToString());
    }, i);
}

Using a state parameter results in fewer allocations. Looking at the decompiled code:

  • the second snippet will create 50 closures and 50 delegates
  • the third snippet will create 50 boxed ints but only a single delegate
like image 155
Panagiotis Kanavos Avatar answered Sep 30 '22 05:09

Panagiotis Kanavos


That's because you are running the code in a new thread, and the main thread immediately goes on to change the variable. If the lambda expression were executed immediately, the entire point of using a task would be lost.

The thread doesn't get its own copy of the variable at the time the task is created, all the tasks use the same variable (which actually is stored in the closure for the method, it's not a local variable).

like image 43
Guffa Avatar answered Sep 30 '22 04:09

Guffa