Yamuk
Yamuk

Reputation: 769

Should controller action be async when returning a view component with multiple InvokeAsync calls in .NET Core

Assume I have a controller action that just returns view.

[HttpGet]
public IActionResult Index()
{
    return View();
}

And in the view, I call a bunch of components like this:

...
@await Component.InvokeAsync("foo")
@await Component.InvokeAsync("bar")
...
@await Component.InvokeAsync("fizz")
...

How is this handled? In this case, should I return a Task and modify my code to become async like so:

[HttpGet]
public async Task<IActionResult> Index()
{
    return await Task.FromResult(View());
}

As a side question, should all controller actions be made async even if their code is sync for the sake of code consistency or performance reasons?

Upvotes: 1

Views: 1327

Answers (1)

Andrew Williamson
Andrew Williamson

Reputation: 8691

No, in this case the controller method should not be async. IActionResult is something that can be executed asynchronously, separate to how you decide what result to return. Some psuedocode might help understand this better:

Request comes into MVC pipeline
Pipeline decides which controller and action to use
Pipeline constructs the controller and executes the action
  The action can be synchronous or asynchronous
  The action returns an IActionResult
Pipeline calls an asynchronous method on the IActionResult that was returned by the action
  The razor page is executed and written to the response stream

So as long as your action produces an IActionResult, the pipeline will handle rendering it asynchronously if it needs to. If the logic in your action doesn't need to be asynchronous, then you don't need to return a task.

Upvotes: 3

Related Questions