[英]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.