Correct way to return an async task within a non-async method

3.8k Views Asked by At

What is the best practice when returning the following Task:

public async Task<Command> BuildCommunicationCommand

As an object:

public Command BuildCommand

I have the following:

 public Command BuildCommand()
    {
        return BuildCommunicationCommand().GetAwaiter().GetResult();
    }

But have been told to try and avoid this and that I should await the Task so we do not block the UI thread. I think the best way to do this is to make the BuildCommand method async and anything else that calls it. This would be a massive change and is not really required for other classes which use the BuildCommand. I do not want to cause a block by using .Result so have read its best to use ConfigureAwait(false) in this case:

 public Command BuildCommand()
        {
            var Command = BuildCommunicationCommand().ConfigureAwait(false);

            return Command.GetAwaiter().GetResult();
        }

Can I use ConfigureAwait(false) to wait for the process to finish and then call .GetAwaiter().GetResult() to return it as the object Command?

This is my first time working with async tasks so if any of the above is complete rubbish I am sorry!

1

There are 1 best solutions below

5
On BEST ANSWER

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.