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.
The lambda expression captures the
avariable. This code is entirely valid.From the draft C# 6 spec, section 11.16.6.2:
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:
The output of this is:
As you can see: