ViewComponent和InvokeAsync方法

nam*_*nam 5 c# asp.net-core asp.net-core-viewcomponent

在下面的方法中,我收到警告:This async method lacks 'await' operators and will run synchronously.我await在哪里可以使用这个方法?注意:此方法返回一个简单的静态视图,而不与数据库等交互.

public class TestViewComponent : ViewComponent
{
    public async Task<IViewComponentResult> InvokeAsync()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ary 13

由于您没有要执行异步工作,因此可以删除async限定符并返回Task.FromResult:

public Task<IViewComponentResult> InvokeAsync()
{
  return Task.FromResult<IViewComponentResult>(View());
}
Run Code Online (Sandbox Code Playgroud)

或者,你可以忽略警告(即用a将其关闭#pragma).