Nesting async/await methods

Viewed 17937

I'm writing a library that wraps a third party web service call and am trying to make the library use the new async/await features. What is the proper use of the async/await keywords in the following example?

public class MyApi
{
    public Task<ApiResult> DoSomethingAsync()
    {
        return this.DoSomethingCore();
    }

    public async Task<ApiResult> DoSomethingElseAsync()
    {
        return await this.DoSomethingCore();
    }

    private async Task<ApiResult> DoSomethingCore()
    {
        var httpClient = new HttpClient();
        var httpResponseMessage = await httpClient.GetAsync("some url");
        var rawResultText = await httpResponseMessage.Content.ReadAsStringAsync();
        return new ApiResult(rawResultText);        
    }
}

To allow my caller to await the DoSomethingAsync method, should that method also have the async and await keywords added to it? Or is it fine as-is because it returns a Task? Is there a better pattern for this sort of nesting?

I think the DoSomethingAsync method is the correct way to go here, is that correct? I believe DoSomethingElseAsync seems the wrong approach when building a library.

2 Answers
Related