Home > Blockchain >  C#, is MultiThread Lambda using free variable Valid?
C#, is MultiThread Lambda using free variable Valid?

Time:02-16

I want to use some free variables in MultiThread Lambda expression.

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.

Even after scope is over, is 'int a' Valid?

Thank you.

CodePudding user response:

The lambda expression captures the a variable. This code is entirely valid.

From the draft C# 6 spec, section 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). 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.

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.

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:

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
  • Related