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.
Any
Taskcan be awaited, regardless of where it came from.I’m not sure why
DoSomethingAsyncjust callsDoSomethingCore, sinceDoSomethingAsynccould just as easily beasyncand useawait.There is also a general rule that you should use
ConfigureAwait(false)in library methods.Edit: If you don’t need to use
await, then don’t make the methodasync.asyncwill add some overhead (check Channel9 for Stephen Toub’s Zen of Async Performance video). If you can just return aTask(likeDoSomethingAsync), then do it that way.