Search code examples
asp.net-corerazorasync-awaitasp.net-core-viewcomponent

Can anyone explain why the Razor calls InvokeAsync but the class implements Invoke


I'm familiarising myself someone else's code and she has this in the Index.cshtml:

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

and this in the ViewComponent class

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

So in the markup, there is an InvokeAsync but the class only implements Invoke. She isn't at the company any longer so I can't ask her for the reasons behind her design (and I'm probably displaying my ignorance of synchronous/asynchronous!)

Thank you.


Solution

  • You don't use any asynchronous call in the method, there is no await. ViewComponent has 2 methods InvokeAsync and Invoke.

    So you can only use the synchronous method InVoke in your GroupMessageViewComponent,Otherwise you will get a warning:

    warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.

    You can see this thread.

    You can see about compoents synchronization method here: Perform synchronous work.