.NET Do lambdas prevent garbage collection of external references used in them?

Here is an example:

var task = Task.Run();
var func = () => task.Result;

So if I loose the task reference and keep the func reference is GC going to collect the task and make the func throw null reference exception?

Jon Skeet
people
quotationmark

No. An anonymous function captures the variable, extending its lifetime to at least when the delegate or expression tree is garbage collected.

From the C# 5 spec, section 7.15.5.1:

When an outer variable is referenced by an anonymous function, the outer variable is said to have been captured by the anonymous function. Ordinarily, the lifetime of a local variable is limited to execution of the block or statement with which it is associated (ยง5.1.7). However, the lifetime of a captured outer variable is extended at least until the delegate or expression tree created from the anonymous function becomes eligible for garbage collection.

Note that it's the variable which is captured though, not the value of the variable at the time. So if you change the code to:

var task = Task.Run(...);
var func = () => task.Result;
task = null;

... then the original Task can be garbage collected, and the delegate will throw an exception if you call it, because it will use the current value of the task variable.

people

See more on this question at Stackoverflow