【问题标题】:In ViewComponent: This async method lacks 'await' operators and will run synchronously在 ViewComponent 中:此异步方法缺少“等待”运算符,将同步运行
【发布时间】:2019-09-25 05:06:00
【问题描述】:

在 ViewComponent 中我收到了这个警告: (我用过ASP.NET Core 2

警告 CS1998:此异步方法缺少“等待”运算符,将运行 同步。考虑使用 'await' 运算符来等待 非阻塞 API 调用,或 'await Task.Run(...)' 来做 CPU 密集型工作 在后台线程上。

我该如何解决?

public class GenericReportViewComponent : ViewComponent
{
   public GenericReportViewComponent()
   {
   }
   public async Task<IViewComponentResult> InvokeAsync(GenericReportViewModel model)
   {
       return View(model);
   }
}

更新:

在看来,我有@await:

 <div class="container">
        @await Component.InvokeAsync("GenericReport", new GenericReportViewModel() { })
    </div>

【问题讨论】:

  • 从方法定义中删除async
  • 错误信息的哪一部分你不清楚?当你不做异步时删除异步,当你做时在方法中使用等待
  • InvokeAsync 确实没有异步操作。您要么使该方法不再是 async,要么您将 await 方法内的一个操作。
  • 从您发布的内容来看,InvokeAsync 方法实际上并没有做任何异步操作。您可以安全地删除async 并返回IViewComponentResult
  • 更新:在看来,我有@await: ...但你在InvokeAsync body 中没有等待

标签: c# asp.net asp.net-core async-await asp.net-core-2.0


【解决方案1】:

您没有在方法中使用任何异步调用(没有await),因此会出现警告。 ViewComponent 有 2 个方法 InvokeAsyncInvoke。当实现中没有异步调用时,您应该使用 ViewComponent 的同步版本 (Invoke):

public class GenericReportViewComponent : ViewComponent
{
   public IViewComponentResult Invoke(GenericReportViewModel model)
   {
       return View(model);
   }
}

这是关于同步工作的文档部分:https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.2#perform-synchronous-work

【讨论】:

  • 不知道为什么这被否决了,也许是因为它只是一个没有任何解释的代码转储?
【解决方案2】:

您的操作InvokeAsync 中没有await 方法

您可以安全地删除async 并将return 更改为IViewComponentResult

public IViewComponentResult Invoke(GenericReportViewModel model)
{
   return View(model);
}

【讨论】:

    【解决方案3】:

    这不需要是异步的,因为您没有做任何可以从异步操作中受益的事情。删除异步和任务。

    【讨论】:

      猜你喜欢
      • 2017-04-30
      • 1970-01-01
      • 2017-11-09
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 2014-02-13
      • 2019-08-27
      相关资源
      最近更新 更多