This is probably a more of a finesse question but I have the following method inside a ViewComponent class
public async Task<IViewComponentResult> InvokeAsync()
{
return View();
}
but the name InvokeAsync is underlined and gives the following warning
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
but if I try removing the async from the method then return View() is underlined with red and outputs the following error
'Microsoft.AspNetCore.Mvc.ViewComponents.ViewViewComponentResult' to 'System.Threading.Tasks.Task' MVCStateManagement
So my question is what approach should I take? Let the async there indiferently of the warning, or is there a workaround / fix for this warning? Does it have that much of an impact on my project?
Thanks!
It's unclear why the method was defined as an async
method that returns a Task<IViewComponentResult>
in the first place.
Since the method seems to be truly synchronous and simply returns a view, you should probably define it like this:
public IViewComponentResult Invoke()
{
return View();
}
A synchronous method doesn't magically become asynchronous just because you add the async
keyword to it.
If you are implementing an interface and cannot change the signature of the method, you could use the Task.FromResult
method to return an already completed task (you should still remove the async
keyword):
public Task<IViewComponentResult> InvokeAsync()
{
return Task.FromResult<IViewComponentResult>(View());
}