简体   繁体   English

在异步操作完成之前从方法返回的不良做法?

[英]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. 我有一个Web API 2端点,我希望在检索和验证用户时异步执行操作。 If this user does not exist I want to return a 404 Not Found like so: 如果此用户不存在,我想返回404 Not Found,如下所示:

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? 如果用户等于null并且在没有等待getCatTask的情况下返回方法或者它被认为是一种不好的做法,这会导致我潜在的问题吗?

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). 对于每个虚假请求(这可能不会经常发生),您将承担额外的GetCatAsync操作的成本。

If possible, consider making GetCatAsync cancelable, and then you'll be able to at least start cleaning up before returning: 如果可能,请考虑使GetCatAsync可取消,然后您将能够在返回之前至少开始清理:

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);
}

This is perfectly acceptable. 这是完全可以接受的。 In terms of async and await , you're not doing anything incorrect. asyncawait ,你没有做任何不正确的事情。 A few notes about the keywords: 关于关键字的一些注意事项:

The async keyword simply enabled the usage of the await keyword. async关键字只是启用了await关键字的使用。 The await keyword is where all the "magic" happens, ie; await关键字是所有“魔法”发生的地方,即; the async state machine will suspend the method execution and return to that point when the "awaited" asynchronous operation has completed. 异步状态机将暂停方法执行并在“等待”异步操作完成时返回到该点。

One important consideration: 一个重要的考虑:

Does the GetCatAsync() return a Task or Task<T> that represents an asynchronous operation that has already started? GetCatAsync()是否返回表示已启动的异步操作的TaskTask<T> If so that might be a little problematic, if not you're fine then as it is awaited later. 如果是这样可能会有点问题,如果不是你就好了,因为它等待以后。 I would suggest adding cancellation though. 我建议添加取消。

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);
}

But, Stephen Cleary beat me to it -- called out above. 但是,斯蒂芬克利里打败了我 - 在上面喊出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM