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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With