首页 > 解决方案 > 在非异步方法中返回异步任务的正确方法

问题描述

返回以下任务时的最佳做法是什么:

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() 将其作为对象命令返回吗?

这是我第一次使用异步任务,所以如果以上任何一个都是垃圾,我很抱歉!

标签: c#asynchronoustaskconfigureawait

解决方案


You can wrap the call to your async method in another method that waits for the task to complete and then returns the result. Of course that blocks the thread that calls GetData. But it gets rid of the async 'virus'. Something like this:

 private string GetData()
 {
     var task = GetDataAsync();
     task.Wait();
     return task.Result;
 }
 private async Task<string> GetDataAsync()
 {
     return "Hello";
 }

You're asking after best practices though, and that is to change everything to async as needed.


推荐阅读