参数传递到一个Task.Factory.StartNew [英] Passing parameter into a Task.Factory.StartNew

查看:2504
本文介绍了参数传递到一个Task.Factory.StartNew的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下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:


  • 请问垃圾收集知道什么时候成了串出
    环境和正确的把它清理干净?

  • 有没有更好的方式来注入依赖成破的任务在主线程中的链接对象?

这是一个Asp.Net web服务,如果它的事项,并有火灾,忘记型螺纹,我不会等待任何一种反应。

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.

我的字符串实际上是会得到的的HttpContext ,这就是为什么我在它注射用这种方式(线程没有访问读出调用线程 HtppContext

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)

推荐答案

您的lambda将被吊出到编译器生成的类。在 injectedString 变量将成为类的字段。

Your lambda will be hoisted out into a compiler generated class. The injectedString variable will become a field of that class.

因此​​,这将是回收垃圾时产生的等级超出范围(这基本上在你的λ的尽头),并且GC决定执行集合

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.

在回应您的评论:

有没有重复。编译器变成这样:

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);
 }

进入这个:

CompilerGeneratedClass c1 = new CompilerGeneratedClass();
c1.injectedString = "Read string out of HttpContext";
// call delegate here.

也请记住:字符串是在CLR实习。即使code被复制..字符串将在池中拘留。你会实际上只有一个本地字大小的参考复制,在指向字符串(仅字符串..)

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..)

这篇关于参数传递到一个Task.Factory.StartNew的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆