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