我在几个地方执行此操作,但重新编写代码是不可行/不切实际的。然而,该方法似乎只能“正常”调用,例如:-
set
{
...
DoSomethingAsync();
}
VS 编辑器中此行下出现波浪线,并带有此工具提示警告:-
Because this call is not awaited, execution of the current method continues before the call is completed.
如果没有 async/await 关键字,我有点希望该方法最终会被同步调用。我没有得到什么?
如果我将行更改为以下内容,则波浪形/警告消失:-
DoSomethingAsync().Wait();
大概这会把它变成一个阻塞调用?
纯粹出于好奇,执行以下操作会产生什么影响:-
Task.Run(() => DoSomethingAsync());
最佳答案
Without the async/await keywords I kind of expected that the method would end up being called synchronously. What am I not getting here?
您的假设是错误的:async
方法总是被异步调用。除非您 Wait()
它,否则它不会等到 async
方法完成。 Wait()
确实会阻止对异步方法的调用。即使您执行 Task.Run
,它也会异步运行(两次,因为它的 async
方法在您的 Task.Run
中异步运行)。
不能异步调用属性,因此 Get
方法可以解决这个问题。这样你就可以让你的代码一直异步。
关于c# - 从属性 setter 调用异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37722329/