[英]Correct way to return an async task within a non-async method
返回以下任務時的最佳做法是什么:
public async Task<Command> BuildCommunicationCommand
作為對象:
public Command BuildCommand
我有以下幾點:
public Command BuildCommand()
{
return BuildCommunicationCommand().GetAwaiter().GetResult();
}
但是被告知要盡量避免這種情況,我應該等待任務,這樣我們就不會阻塞 UI 線程。 我認為最好的方法是使 BuildCommand 方法和其他任何調用它的方法異步。 這將是一個巨大的變化,對於使用 BuildCommand 的其他類來說並不是真正需要的。 我不想通過使用 .Result 導致阻塞,所以在這種情況下最好使用 ConfigureAwait(false):
public Command BuildCommand()
{
var Command = BuildCommunicationCommand().ConfigureAwait(false);
return Command.GetAwaiter().GetResult();
}
我可以使用 ConfigureAwait(false) 等待進程完成,然后調用 .GetAwaiter().GetResult() 將其作為對象 Command 返回嗎?
這是我第一次使用異步任務,所以如果以上任何一項都是垃圾,我很抱歉!
您可以將異步方法的調用包裝在另一個等待任務完成然后返回結果的方法中。 當然,這會阻塞調用 GetData 的線程。 但它擺脫了異步“病毒”。 像這樣的東西:
private string GetData()
{
var task = GetDataAsync();
task.Wait();
return task.Result;
}
private async Task<string> GetDataAsync()
{
return "Hello";
}
不過,您正在尋求最佳實踐,那就是根據需要將所有內容更改為異步。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.