不确定自己是否混淆了对async await的理解,但是这里有一个我卡住的问题。考虑以下人为的例子:
This code blocks UI
public async void LoginButtonClicked() { //create a continuation point so every following statement will get executed as ContinueWith await Task.FromResult(0); //this call takes time to execute Remote.Login("user","password"); }
But this does not (obviously)
public void LoginButtonClicked() { Task.Run(()=>{ Remote.Login("user","password");}); }
我喜欢使用方法1,因为我不想使用Task.Run来旋转长时间的工作,而是更喜欢框架来处理。但问题是调用方法1似乎会阻塞。
await
右侧的任务尚未完成时,它才会执行任何特殊操作。而Task.FromResult
总是返回一个已完成的任务,因此该方法会在await
点之后继续顺利执行。 - Damien_The_Unbelieverawait
调用Task.FromResult
方法:我应该在Task.FromResult方法调用上使用await吗? - S.Serpooshan