x19
x19

Reputation: 8783

In ViewComponent: This async method lacks 'await' operators and will run synchronously

In ViewComponent I got this warning: (I've used ASP.NET Core 2)

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.

How can I solve it?

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

Update:

in view, I have @await:

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

Upvotes: 3

Views: 2185

Answers (3)

Jeric Cruz
Jeric Cruz

Reputation: 1909

You have no await methods inside your action InvokeAsync

You can safely remove async and change return to IViewComponentResult

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

Upvotes: 4

meziantou
meziantou

Reputation: 21367

You don't use any asynchronous call in the method (there is no await), hence the warning. ViewComponent has 2 methods InvokeAsync and Invoke. You should use the synchonous version (Invoke) of the ViewComponent when there is no asynchrounous calls in the implementation:

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

Here's the documentation section about synchronous work: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.2#perform-synchronous-work

Upvotes: 5

Matt M
Matt M

Reputation: 1445

This doesn't need to be async as you're not doing anything that would benefit from an async operation. Drop async and Task<>.

Upvotes: 2

Related Questions