c# - 异步编程并在循环中等待

标签 c# .net multithreading asynchronous async-await

我开始学习 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/

相关文章:

c# - .NET Framework v4.5.2 中的 ZipArchive 构造函数在 Windows 10 和 Windows Server 2012 和 2008 机器上产生不一致的结果?

multithreading - 多线程运行Stanford CoreNLP服务器

java - 线程代码演练,Thread.Sleep() 的机制

java - 如何将连接信息传递给可运行对象?

c# - Xamarin "attempt to invoke virtual method ' void android.view.View.unFocus (android.view.View )' on a null object reference"

c# - 如何获取成员(member)的全名

c# - 如何简化基本凯撒移位加密算法 C# 的实现?

c# - 如何转换实现接口(interface)的具体类的列表

c# - UriBuilder 没有正确组合两个 URI

.net - 我在哪里可以找到 taglib-sharp 支持的所有音频文件类型的列表?