在C#規範4.0節7.15.5.1:捕獲的變量如何同時暴露給多個執行線程?
注意,不像未捕獲的變量,捕獲的局部變量可以被 simulataneously暴露於多個執行線程。
「多線程執行」究竟意味着什麼?這是否意味着多個線程,多個執行路徑或其他?
E.G.
private static void Main(string[] args)
{
Action[] result = new Action[3];
int x;
for (int i = 0; i < 3; i++)
{
//int x = i * 2 + 1;//this behaves more intuitively. Outputs 1,3,5
x = i*2 + 1;
result[i] =() => { Console.WriteLine(x); };
}
foreach (var a in result)
{
a(); //outputs 5 each time
}
//OR...
int y = 1;
Action one = new Action(() =>
{
Console.WriteLine(y);//Outputs 1
y = 2;
});
Action two = new Action(() =>
{
Console.WriteLine(y);//Outputs 2. Working with same Y
});
var t1 = Task.Factory.StartNew(one);
t1.Wait();
Task.Factory.StartNew(two);
Console.Read();
}
這裏x
展品基於其中x
聲明不同的行爲。在y
的情況下,多個線程捕獲並使用相同的變量,但IMO這種行爲很直觀。
它們指的是什麼?