本文介绍了是否在不使用await的情况下调用异步方法中的await仍然异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
public static void Run() {
DoStuffAsync();
}
public static async Task DoStuffAsync() {
PerformCalc();
await DoLongTaskAsync();
PerformAnotherCalc();
}
比方说,我叫 Run()
.我对行为有一些疑问:
Let's say I call Run()
. I have a few questions regarding behaviour:
- 是否会在与调用
Run()
的线程相同的线程上同步调用PerformCalc()
? - 会异步还是同步调用
DoLongTaskAsync()
?换句话说,是否可以在DoLongTaskAsync()
完成之前调用PerformAnotherCalc()
? - 随后,
DoStuffAsync()
方法能否在完成DoLongAsyncTask()
执行之前返回?
- Will
PerformCalc()
be called synchronously on the same thread as the one that calledRun()
? - Will
DoLongTaskAsync()
be called asynchronously or synchronously? In other words, will/canPerformAnotherCalc()
be called beforeDoLongTaskAsync()
has finished? - Subsequently, can the
DoStuffAsync()
method return before execution ofDoLongAsyncTask()
has completed?
推荐答案
异步方法始终 start 同步运行.魔术发生在 await
上,但是仅当 await
被赋予尚未完成的 Task
任务时.
Async methods always start running synchronously. The magic happens at await
, but only when await
is given a Task
that has not completed.
在您的示例中,这就是您调用 Run()
时将发生的情况:
In your example, this is what will happen when you call Run()
:
- 跳转到
DoStuffAsync()
- 跳转到
PerformCalc()
- 跳转到
DoLongTaskAsync()
- 如果
DoLongTaskAsync()
是真正的异步操作,并且返回不完整的Task
,则await
会执行job和DoStuffAsync()
返回不完整的Task
到Run()
. - 由于未等待任务,因此
Run()
完成. - 当
DoLongTaskAsync()
完成时,DoStuffAsync()
恢复,并跳转到PerformAnotherCalc()
.
- Jump to
DoStuffAsync()
- Jump to
PerformCalc()
- Jump to
DoLongTaskAsync()
- If
DoLongTaskAsync()
is a truly asynchronous operation and returns an incompleteTask
, thenawait
does its job andDoStuffAsync()
returns an incompleteTask
toRun()
. - Since the task is not awaited,
Run()
completes. - When
DoLongTaskAsync()
completes,DoStuffAsync()
resumes, and jumps toPerformAnotherCalc()
.
所有这些可以发生在同一线程上.
All of that can happen on the same thread.
所以回答您的问题:
- 是的.如果它是
async
方法,则它可能最终会消失并在其他线程上运行.但是它将在同一线程上同步启动. -
DoLongTaskAsync()
将被异步调用,但是在DoLongTaskAsync()
完成之前不会调用PerformAnotherCalc()
,因为您使用了等待
. - 是的.这就是
await
的工作方式.它将返回不完整的Task
(即,仅当DoLongTaskAsync()
是真正异步的并且返回不完整的Task
时).然后,一旦DoLongTaskAsync()
完成后,DoStuffAsync()
的执行就会从中断的地方恢复.
- Yes. If it is an
async
method, it might end up going out and doing things on other threads. But it will start synchronously on the same thread. DoLongTaskAsync()
will be called asynchronously, butPerformAnotherCalc()
will not be called beforeDoLongTaskAsync()
finishes, because you usedawait
.- Yes. This is how
await
works. It will return an incompleteTask
(that is, only ifDoLongTaskAsync()
is truly asynchronous and returns an incompleteTask
). Then onceDoLongTaskAsync()
finishes, execution ofDoStuffAsync()
resumes where it left off.
这篇关于是否在不使用await的情况下调用异步方法中的await仍然异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!