0

I guess my question boils down to:

Given two async methods where one calls the other. Should I await in both of the methods, or just the first?

Here's my scenario. I'm writing an ASP NET CORE WEB API using CQRS and MediatR.

I have this async API method

[HttpGet]
public async Task<IActionResult> Get(Get.Query query)
{
    var result = await _mediator.Send(query);
    return Ok(result);
}

Should I also async/await in my RequestHandler? Like this

public class QueryHandler : IAsyncRequestHandler<Query, IEnumerable<Result>>
{
    public async Task<IEnumerable<Result>> Handle(Query message)
    {
        return await _connection.QueryAsync<Result>("...");
    }
}

Or should I simply do this

public class QueryHandler : IAsyncRequestHandler<Query, IEnumerable<Result>>
{
    public Task<IEnumerable<Result>> Handle(Query message)
    {
        return _connection.QueryAsync<Result>("...");
    }
}

The reason I'm puzzled is because the API request is already in a thread. So is wrapping it in another thread not the correct way to do it? I've seen examples of both :/

Snæbjørn
  • 10,322
  • 14
  • 65
  • 124
  • 1
    Async/await does not cause things to get wrapped in threads. Only doing a explicit `Task.Run(` causes it to be wrapped in a thread. – Scott Chamberlain Aug 01 '17 at 21:24
  • 1
    Hmm seems I need to read up on async/await – Snæbjørn Aug 01 '17 at 21:28
  • I believe awaiting and returning the task itself ultimately don't matter as the thread handling the request will ultimately be released during io operations. But i like to go with the second option because i believe it requires less context switching between threads – Sal Aug 02 '17 at 03:36

0 Answers0