gpt4 book ai didi

c# - async 和 await 是单线程的真的吗?

转载 作者:太空狗 更新时间:2023-10-29 17:49:13 30 4
gpt4 key购买 nike

我创建了以下代码:

using System;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
class Program
{
static void Main()
{
Console.WriteLine("M Start");
MyMethodAsync();
Console.WriteLine("M end");
Console.Read();
}

static async Task MyMethodAsync()
{
await Task.Yield();
Task<int> longRunningTask = LongRunningOperationAsync();
Console.WriteLine("M3");
//and now we call await on the task
int result = await longRunningTask;
//use the result
Console.WriteLine(result);
}

static async Task<int> LongRunningOperationAsync()
{
await Task.Delay(1000);
return 1;
}
}
}

输出:

M Start
M end
M3
1

这很好,但是当我查看线程分析器时,它显示如下: enter image description here然后这个: enter image description here然后这个: enter image description here

所以看起来我生成了线程,但是从 msdn 说:

From Asynchronous Programming with Async and Await : Threads

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. You can use Task.Run to move CPU-bound work to a background thread, but a background thread doesn't help with a process that's just waiting for results to become available.

我是否遗漏或不理解某些内容?谢谢。

最佳答案

我解释how async and await work with threads and contexts在我的博客上。总之,当 await 需要等待异步操作完成时,它会“暂停”当前的 async 方法并(默认情况下)捕获一个“上下文”。

当异步操作完成时,该“上下文”用于恢复 async 方法。这个“上下文”是 SynchronizationContext.Current,除非它是 null,在这种情况下它是 TaskScheduler.Current。在您的情况下,上下文最终成为线程池上下文,因此 async 方法的其余部分被发送到线程池。如果您从 UI 线程运行相同的代码,上下文就是 UI 上下文,所有 async 方法都将在 UI 线程上恢复。

关于c# - async 和 await 是单线程的真的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35483763/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com