简体   繁体   English

C#,MultiThread Lambda 使用自由变量有效吗?

[英]C#, is MultiThread Lambda using free variable Valid?

I want to use some free variables in MultiThread Lambda expression.我想在 MultiThread Lambda 表达式中使用一些自由变量。

Here is example,这是例子,

{
   int a = 0;
   Thread t = new Thread(() => 
   {
        SomeBlockingFunc(a);
   });
   t.Start();
}

I can't recognize when Thread t Excute, even variable scope is over.无法识别什么时候Thread t Excute,连变量scope都结束了。

Even after scope is over, is 'int a' Valid?即使在 scope 结束之后,'int a' 有效吗?

Thank you.谢谢你。

The lambda expression captures the a variable. lambda 表达式捕获a变量。 This code is entirely valid.此代码完全有效。

From the draft C# 6 spec, section 11.16.6.2 :来自草案 C# 6 规范, 第 11.16.6.2 节

When an outer variable is referenced by an anonymous function, the outer variable is said to have been captured by the anonymous function. Ordinarily, the lifetime of a local variable is limited to execution of the block or statement with which it is associated (§9.2.8).当外部变量被匿名 function 引用时,外部变量被称为匿名 function 被捕获。通常,局部变量的生命周期仅限于与其关联的块或语句的执行(§9.2 .8). However, the lifetime of a captured outer variable is extended at least until the delegate or expression tree created from the anonymous function becomes eligible for garbage collection.但是,捕获的外部变量的生命周期至少会延长,直到从匿名 function 创建的委托或表达式树符合垃圾回收条件为止。

It's important to differentiate between the scope of a variable (which is just the section of code within which the identifier refers to that variable) and the lifetime of the variable.区分变量的scope (它只是标识符在其中引用该变量的代码部分)和变量的生命周期很重要。

It's also worth noting that it really is still a variable .还值得注意的是,它确实仍然是一个变量 Multiple delegates can potentially capture the same variable.多个委托可能会捕获相同的变量。 Consider this code:考虑这段代码:

using System;

int value = 0;
Action a = () =>
{
    Console.WriteLine($"In first action; value={value}");
    value++;
};
Action b = () =>
{
    Console.WriteLine($"In second action; value={value}");
    value++;
};

a();
a();
b();
a();

The output of this is:这个的output是:

In first action; value=0
In first action; value=1
In second action; value=2
In first action; value=3

As you can see:如你看到的:

  • The two actions have captured the same variable这两个动作捕获了相同的变量
  • Changes to the variable value made within each action are seen by both actions两个操作都可以看到每个操作中对变量值所做的更改

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM