我开始学习 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
那么是否有不同的线程访问同一个循环?索引变量是否存在竞争条件?
最佳答案
不,没有竞争条件。您启动了一个新任务,该任务将在后台运行,但您的代码在该任务完成之前不会继续执行,因此您可以确保您的代码在任何时候都只会在一个线程中执行。
但是,因为这是一个控制台应用程序,所以没有当前的 SyncronizationContext
。 (与将存在的 winform、WPF、ASP、Silverlight 等应用程序相反。)这意味着任何 await
调用的延续将在线程池中运行,而不是在调用中运行线。所以是的,您在循环的每次迭代中都在线程池线程之一中运行,并且每次都可能是不同的线程,但是您可以确定,除了放入新任务中的任何内容外,您将“在开始处理下一个线程之前完成“在任何给定线程上运行,这确保在任何给定时间只有一个线程运行代码(这意味着没有竞争条件)。
关于c# - 异步编程并在循环中等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14381668/