![](/img/trans.png)
[英]Why do I have to use (async method).result instead of await (async method)?
[英]Do I always have to await on an Async method of a disposable object instead of returning its Task?
似乎我陷入了一個巨大的陷阱,經過數小時的調試,我看到該過程在 RunGame1() 中不再“使用” scope,並且在等待時任務永遠不會完成。
async void Execute(object o) // ICommand.Execute
{
// fire and forget
try
{
await RunGame2(); // RunGame1() fails to complete
}
finally
{ ... }
}
// This fails due to process going out of "using" scope and never completes
Task RunGame1()
{
var info = new ProcessStartInfo("game.exe") { CreateNoWindow = true };
using var process = new Process() { StartInfo = info };
process.Start();
return process.WaitForExitAsync();
}
// Have to await the Task inside the method
async Task RunGame2()
{
var info = new ProcessStartInfo("game.exe") { CreateNoWindow = true };
using var process = new Process() { StartInfo = info };
process.Start();
await process.WaitForExitAsync();
}
是否有解決此問題的模式,以便我可以返回任務以保存編譯器,從而制作額外的 state 機器,或者只是需要注意的事情?
這確實是一個常見的問題 - 由於類似的原因,我已經看到了幾個錯誤。
簡而言之:
await
任務,有時避免異步機制的開銷可能是積極有利的 - 特別是在文件/網絡 IO 循環等緊湊代碼中,但是(這是一個很大的但是)try
/ finally
區域(其中還包括using
和lock
,盡管在async
代碼中lock
存在其他更大的問題),那么您需要考慮到這一點,這通常意味着“是的,您需要await
“ 如果有一個分析器發現Task[<T>]
/ ValueTask[<T>]
在這樣一個區域內的非async
方法中return
,那就太好了,因為它幾乎總是一個錯誤,並且對於有幾次它不是( finally
與返回的東西無關)它可以被壓制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.