【问题标题】:Can anyone explain why the Razor calls InvokeAsync but the class implements Invoke谁能解释为什么 Razor 调用 InvokeAsync 但该类实现 Invoke
【发布时间】:2021-08-14 21:09:41
【问题描述】:

我正在熟悉别人的代码,她在 Index.cshtml 中有这个:

        @if (Model.Type == Group)
        {
            @await Component.InvokeAsync("GroupMessage")
        }

这在 ViewComponent 类中

public class GroupMessageViewComponent : ViewComponent
{
    public IViewComponentResult Invoke()
    {
        return View();
    }
}

所以在标记中,有一个 InvokeAsync 但该类只实现了 Invoke。她已经不在公司了,所以我不能问她设计背后的原因(我可能表现出我对同步/异步的无知!)

谢谢。

【问题讨论】:

    标签: asp.net-core razor async-await asp.net-core-viewcomponent


    【解决方案1】:

    你没有在方法中使用任何异步调用,没有awaitViewComponent 有 2 个方法 InvokeAsyncInvoke

    所以你只能在你的GroupMessageViewComponent中使用同步方法InVoke,否则会收到警告:

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

    你可以看到这个thread

    组件同步方法可以看这里:Perform synchronous work

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-13
      • 1970-01-01
      • 2012-03-27
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      相关资源
      最近更新 更多