gpt4 book ai didi

c# - 异步/等待示例

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:58 25 4
gpt4 key购买 nike

好吧,我想我差不多已经了解了关于 async/await 和多线程的所有模糊问题。我知道异步是关于任务的,而多线程是关于 worker 的。因此,您可以在同一个线程上运行不同的任务(this answer 对此做了很好的解释)。

所以我编写了一个小程序以查看魔术的发生,但我有点困惑:

public class Program
{
public static async Task Main(string[] args)
{
var task = ToastAsync();
Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Cleaning the kitchen...");
await task;
Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Take the toast");
}

public async static Task ToastAsync()
{
Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Putting the toast");
Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Setting a timer");
await Task.Delay(2000);
Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] Toast is ready");
}
}

在第一次运行这个程序之前,我希望它在单线程上运行。就像我在上面链接的答案一样,我预计这相当于“在 toast 计时器运行时清洁厨房”。结果与它相矛盾:

[1] Putting the toast
[1] Setting a timer
[1] Cleaning the kitchen...
[4] Toast is ready
[4] Take the toast

上面的结果对我来说意义不大。到底发生了什么?似乎函数的一部分正在一个线程中执行,然后,当它遇到 await 点时,它会将执行处理到另一个线程......?我什至不知道这是可能的 D:

此外,我稍微改变了上面的例子。在主函数中,我使用了 task.Wait() 而不是 await task;。然后结果改变了:

[1] Putting the toast
[1] Setting a timer
[1] Cleaning the kitchen...
[4] Toast is ready
[1] Take the toast

现在这看起来更像例子了。不过,这就像 toast 上的计时器充当了不同的“炊具”。但为什么它与使用 await 不同?有没有办法在单个线程中完全获取异步任务?我的意思是,在 thread 1 上也有 Toast is ready 吗?

感谢异步!

最佳答案

需要注意的是

  1. 当您调用 ToastAsync 时,它会启动 Task Hot(即使您还没有称为 await)。注意:启动任务并不意味着启动线程……这反过来又解释了为什么要“打扫厨房”。在“ toast ”的后面)

  2. async 方法将一直运行,直到遇到第一个 await 关键字,并将控制权交还给调用者。

  3. 因为 Console App 中没有 SynchronizationContext。编译器认为不需要在调用线程上创建Continuation,这反过来解释了为什么“Take the toast”与“Toast is ready”在同一个线程上.

注意:如果你把厨房弄得一团糟后打扫,就不用事先打扫了

来自评论

I understand then that an await will always take a thread from threadpool to run the the method (this is really blowing my mind) thereforeit is basically impossible to have an async / await single threaded

Async and Await 模式本身与多线程无关,它与可扩展性和 IO 绑定(bind)工作负载和/或 UI 响应能力(在 UI 框架)。

看看 Stephen Cleary 关于这个主题的一些文章:

Async and Await - Stephen Cleary

关于c# - 异步/等待示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55643500/

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