当我运行这段代码时
private void button1_Click(object sender, EventArgs e)
{
Start(sender, e);
}
private void Start(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
System.Threading.Tasks.Task.Factory.StartNew(() => dosomething(i));
Debug.WriteLine("Called " + i);
}
Debug.WriteLine("Finished");
}
public void dosomething(int i)
{
Debug.WriteLine("Enters " + i);
lock (this)
{
Debug.WriteLine("Working " + i);
Thread.Sleep(100);
}
Debug.WriteLine("Done " + i);
}
.Net 4.0 和 4.5 版的输出不同。随着 4.0 数字 5 重复,我可以看到 i 的原因值在一些任务执行之前被移动到 5,但是 4.5 的相同代码显示不同的输出。
(输出使用 VS 2010 .Net 4.0 运行)
Called 0
Called 1
Enters 1
Working 1
Called 2
Called 3
Called 4
Finished
Enters 0
Done 1
Enters 5
Working 0
Working 5
Done 0
**Enters 5
Working 5
Done 5
Enters 5
Done 5
Working 5
Done 5**
但是当我使用.Net 4.5(VS 2011 beta)运行时,结果是,
(输出与 VS 2011 beta .Net 4.5 一起运行)
Enters 0
Working 0
Called 0
Called 1
Enters 2
Called 2
Enters 2
Enters 3
Called 3
Called 4
Finished
Done 0
Working 2
Enters 5
Done 2
Working 3
Done 3
Working 5
Done 5
Working 2
Done 2
我看不到 CLR 4.5 下的 Task 所做的更改?谁能指出.Net 4.5的变化是什么。