Bargitta
Bargitta

Reputation: 2406

Is async keyword necessary in the method signature when calling another async method internally?

Here's a C# async code snippet. Is GetAsync the same as GetAsync2? Is GetAsync a right implementation?

    public Task<IHttpActionResult> GetAsync()
    {
        return GetOneAsync();
    }
    public async Task<IHttpActionResult> GetAsync2()
    {
        return await GetOneAsync();
    }
    private async Task<IHttpActionResult> GetOneAsync()
    {
        using (var httpClient = new HttpClient())
        {
            await httpClient.GetAsync("http://baidu.com");
        }
        return Ok();
    }

Upvotes: 1

Views: 253

Answers (1)

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

It is not the same. GetAsync does not generate a state machine and does not wait for the result of GetOneAsync, which is the preferred option when the result of the async method is not needed in this method.

The resulting code is more efficient as well as no state machine is generated and no context switch is required.

See Understanding the cost of Async/Await article for more info.

Upvotes: 1

Related Questions