c# - 异步等待新线程的行为

标签 c# multithreading asynchronous async-await

我试图理解 async/await 的精确行为,但在思考它时遇到了一些麻烦。

考虑这个例子:

public async void StartThread()
{
    while(true){
        SomeOtherClass.SomeSynchronousStuff();
        var something = await SomeOtherClass.SomeOtherAsyncMethod();
    }
}

public void ConstructorForThisClass()
{
    Thread thread = new Thread(StartThread);
    thread.Start();
}

我对 async/await 的理解是,在幕后发生的事情是编译器实质上将您的代码转换为一堆回调并为每个回调存储状态对象。

所以根据这个,我的问题是:

  1. 新创建的线程会异步运行吗?意思是,当线程等待 SomeOtherAsyncMethod 时,它会被释放出来处理其他工作吗?
  2. 如果上述情况成立,当 SomeOtherAsyncMethod 返回时,线程是否会简单地结束并由一个线程池线程取而代之?
  3. 如何在线程池线程而不是托管线程上发出 StartThread 函数?
  4. 当一个可等待方法返回给它的调用者时,它是被迫在调用它的线程上恢复,还是可以有任何空闲线程代替它?

最佳答案

裸线程不能很好地与 async/await 配合使用。

Will the newly created thread be running asynchronously? Meaning, while the thread is awaiting the SomeOtherAsyncMethod, will it be freed up to work on other work?

实际上,线程只会退出。当 StartThreadawait 之后恢复时,它将在线程池线程上执行。

How would I go about issuing the StartThread function on a thread pool thread rather than a managed thread?

首先,您需要将 StartThread 的返回类型从 void 更改为 Taskasync void 方法用于事件处理程序;在其他地方使用它们会导致各种问题。

然后你可以通过 Task.Run 调用它:

var backgroundTask = Task.Run(() => StartThread());

When an awaitable method returns to its caller, is it forced to resume on the thread that calls it or can any free thread take its place?

默认情况下,await 运算符将捕获“当前上下文”并在该上下文中恢复。此“当前上下文”是 SynchronizationContext.Current,除非它是 null,在这种情况下它是 TaskScheduler.Current。通常,这要么是 UI/ASP.NET SynchronizationContext,要么是线程池上下文 (TaskScheduler.Default)。

你可以找到我的 async intro有帮助。

关于c# - 异步等待新线程的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29151168/

相关文章:

java - 异步Java : Help flatten my nested Mono

javascript - 异步加载一些生成的 Javascript

c# - 具有大量数据的客户端缓存 DropDownList?

multithreading - COM 线程模型 - 永久的困惑

C# 中点舍入为零

android - 线程启动/停止在 Android 上无法正常工作

c# - 如何在不按住 Windows 窗体应用程序 C# 中的按钮的情况下连续更新文本框?

asynchronous - 在 F# 中优化映射异步序列的语法

c# - 在联结表中插入记录 asp.net MVC 4 Entity Framework 6

c# - 将 OUT 参数传递给过程不好吗?