gpt4 book ai didi

c# - 在异步等待中等待的工作

转载 作者:行者123 更新时间:2023-11-30 13:57:05 25 4
gpt4 key购买 nike

考虑一个被调用两次的异步 (*Async/async) 函数,一次使用 await ,另一次不使用它。

如果我用await,会不会等到异步函数执行完再执行下一行?

await db.SaveChangesAsync();
//Some code here

而且,如果我不使用 await,它会继续执行下面的代码而不等待异步函数完成吗?

db.SaveChangesAsync();
//Some code here

是吗,我就在这边,或者当涉及到 async 函数时,await 是强制性的吗?

最佳答案

If I use await, will it wait till the async function is executed and then execute the next line.

这取决于方法返回。它返回 Task[<T>] ,代表一个 future 值。如果Task已经完成,它保持同步运行。否则,当前方法的剩余部分将作为延续添加 - 一个在异步部分报告完成时调用的委托(delegate)回调。

在任何一种情况下,它做的是在异步部分继续时阻塞调用线程。

And, if I don't use await, will it continue with executing the code below it without waiting for the async function to complete.

...or await is mandatory when it comes to async functions?

什么时候调用它们?不是强制性的,但它确实使事情变得方便。通常,此类函数返回 Task[<T>]。 ,也可以通过不同的代码使用。你可以使用 .ContinueWith(...) , .Wait , .Result等。或者您可以忽略 Task完全地。最后一个是个坏主意,因为异步函数的异常需要去某个地方:如果没有观察到异常,就会发生非常糟糕的事情。

然而,当它们时:如果你写一个 async方法并且没有 await那里的关键字,编译器会发出警告,表明您可能做错了什么。同样,不是严格强制,而是强烈推荐。

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

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