ViewComponent and InvokeAsync method
Asked Answered
H

1

7

In the following method I'm getting the warning: This async method lacks 'await' operators and will run synchronously. Where can I use await in this mehod? Note: This method is returning a simple static View without interacting with a Database etc.

public class TestViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        return View();
    }
}
Hartfield answered 12/10, 2016 at 20:22 Comment(0)
L
16

Since you have no asynchronous work to do, you could remove the async qualifier and just return Task.FromResult:

public Task<IViewComponentResult> InvokeAsync()
{
  return Task.FromResult<IViewComponentResult>(View());
}

Alternatively, you could just ignore the warning (i.e., turn it off with a #pragma).

Lunitidal answered 12/10, 2016 at 20:38 Comment(3)
Is there any performance difference in using return Task.FromResult<IViewComponentResult>(View()) vs. just ignoring the warning?Hartfield
@nam: I suspect FromResult would be faster, but it's completely negligible in this case.Lunitidal
Thank you for providing some reasoning for your solution - it works.Hartfield

© 2022 - 2024 — McMap. All rights reserved.