Given the following code:
string injectedString = \"Read string out of HttpContext\";
Task.Factory.StartNew(() =>
{
MyClass myClass = new MyClass();
Your lambda will be hoisted out into a compiler generated class. The injectedString
variable will become a field of that class.
So, it will be garbage collected when the generated class is out of scope (which is basically at the very end of your lambda), and the GC decides to perform a collection.
In response to your comment:
There is no duplication. The compiler turns this:
string injectedString = "Read string out of HttpContext";
Task.Factory.StartNew(() =>
{
MyClass myClass = new MyClass();
myClass.Method(injectedString);
}
Into this:
CompilerGeneratedClass c1 = new CompilerGeneratedClass();
c1.injectedString = "Read string out of HttpContext";
// call delegate here.
Remember also: Strings are interned in the CLR. Even if the code was duplicated.. string literals will be interned in a pool. You would essentially only have a native WORD sized reference duplicated that pointed at the string (string literals only..)