Given the following code:
string injectedString = "Read string out of HttpContext";
Task.Factory.StartNew(() =>
{
MyClass myClass = new MyClass();
myClass.Method(injectedString);
}
Is this the best way to pass the string into the Task/Thread?
My concerns with this method are:
- Would the garbage collector know when the string became out of context and clean it up correctly?
- Is there a better way to inject dependencies into a Task breaking the link to the object in the main thread?
This is in a Asp.Net webservice, if it matters and is a fire and forget type thread, I'm not waiting for any kind of response.
My string is actually going to get read out of the HttpContext
, which is one reason why I'm injecting it in this way (Thread does not have access to the calling threads HtppContext
)
If you're concerned about
injectedString
may be "garbage collected" beforemyClass.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 thelambda
. 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.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:
Into this:
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..)
You should probably use the
Task.Factory.StartNew(Action<object> action, object state)
overload to pass state into your new task.