Passing parameter into a Task.Factory.StartNew

后端 未结 3 2135
借酒劲吻你
借酒劲吻你 2021-02-20 05:38

Given the following code:

string injectedString = \"Read string out of HttpContext\";
Task.Factory.StartNew(() =>
 {
    MyClass myClass = new MyClass();
             


        
3条回答
  •  梦如初夏
    2021-02-20 05:59

    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.

提交回复
热议问题