Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad practice to return from method before async operation completes?

I have an Web API 2 end point where by I want to asynchronously carry out an operation while I retrieve and verify a user. If this user does not exist I want to return a 404 Not Found like so:

public async Task<IHttpActionResult> Get()
{
    var getCatTask = GetCatAsync();
    var user = await GetUserAsync();

    if(user == null)
    {
        return NotFound();
    }     

    var cat = await getCatTask;

    return Ok(cat);
}

Could this cause me potential issues if the user was to equal to null and the method returned without awaiting the getCatTask or is it considered a bad practice?

like image 645
Charly Avatar asked Apr 05 '16 10:04

Charly


1 Answers

It's not really bad, since in this case you're only reading data and you're just going to ignore the result. You would incur the cost of an extra GetCatAsync operation for every fake request (which probably won't happen that often).

If possible, consider making GetCatAsync cancelable, and then you'll be able to at least start cleaning up before returning:

public async Task<IHttpActionResult> Get()
{
  var cts = new CancellationTokenSource();
  var getCatTask = GetCatAsync(cts.Token);
  var user = await GetUserAsync();

  if (user == null)
  {
    cts.Cancel();
    return NotFound();
  }     

  var cat = await getCatTask;
  return Ok(cat);
}
like image 196
Stephen Cleary Avatar answered Oct 13 '22 02:10

Stephen Cleary