我开始学习 C# 5 和 .Net 4.5 中的异步编程,但有些东西我不明白。
private static int count;
public static void Main()
{
LoopTest();
Console.ReadKey(false);
}
static async void LoopTest()
{
count = 0;
for (var index = 0; index < 10; ++index)
{
Console.WriteLine( "({0}) In Loop before await, Index {1}, Thread: {2}", count++, index, Thread.CurrentThread.ManagedThreadId);
await Task.Factory.StartNew(() => Thread.Sleep(10));
}
}
结果是:
(0) In Loop before await, Index 0, Thread: 9
(1) In Loop before await, Index 1, Thread: 10
(2) In Loop before await, Index 2, Thread: 11
(3) In Loop before await, Index 3, Thread: 10
(4) In Loop before await, Index 4, Thread: 11
(5) In Loop before await, Index 5, Thread: 10
(6) In Loop before await, Index 6, Thread: 12
(7) In Loop before await, Index 7, Thread: 11
(8) In Loop before await, Index 8, Thread: 10
(9) In Loop before await, Index 9, Thread: 12
那么是否有不同的线程访问同一个循环?索引变量是否存在竞争条件?