Given the following code:
string injectedString = \"Read string out of HttpContext\";
Task.Factory.StartNew(() =>
{
MyClass myClass = new MyClass();
If you're concerned about injectedString
may be "garbage collected" before myClass.Method(injectedString);
runs ?
Answer is no. You don't need to worry about that, because injectedString
is no more a local variable when it is closed in the lambda
. It will become a field in new compiler generated class.
If you're concerned about will the garbage collector collect it at right time?
Answer is yes, It will do when the instance of that class goes out of scope and no refernces to it in managed code. That would happen certainly after Task
gets completed and gets out of scope.