【问题标题】:Is it necessary to await a single asynchronous call [duplicate]是否有必要等待单个异步调用[重复]
【发布时间】:2014-05-30 08:54:59
【问题描述】:

如果我返回单个异步函数的结果,例如在应用层之间的服务中,有什么区别:

    public Task<byte[]> GetInsurancePolicyDocument(string itineraryReference)
    {
        return this.coreItineraryDocumentService.GetInsurancePolicyDocument(itineraryReference);
    }

还有:

    public async Task<byte[]> GetInsurancePolicyDocument(string itineraryReference)
    {
        return await this.coreItineraryDocumentService.GetInsurancePolicyDocument(itineraryReference);
    }

【问题讨论】:

  • 没有更多的上下文,这个答案是不可能回答的。顺便说一句,不要使用异步/等待,因为它很酷。在需要时使用它。
  • @LexLi,我不同意,但它没有实际意义,这是重复的。
  • 显然这个函数在做 I/O,所以我不认为我在使用 async-await '因为它很酷'。这种服务和类似服务的结果最终会进入 MVC 控制器,在那里它们在被困在 View-Model 之前被异步等待(Task.WhenAll)。

标签: c# asynchronous async-await


【解决方案1】:

在某些情况下存在一些非常细微的差异 - 例如,如果原始 Task 返回状态为 Faulted 但带有 OperationCanceledException,则 async 版本将返回带有状态的任务Canceled... 但除非您真的需要任何微妙之处,否则最好使用您的第一个代码并避免包装它的(非常轻微的)开销。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-09
    • 2018-09-22
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多