异步任务给出警告,(没有)异步任务给出错误

Async Task gives warning, (without) Async Task gives error

这可能是一个更精细的问题,但我在 ViewComponent 中有以下方法 class

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

但名称 InvokeAsync 带有下划线并给出以下警告

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

但是如果我尝试从方法中删除 async 然后 return View() 带有红色下划线并输出以下错误

'Microsoft.AspNetCore.Mvc.ViewComponents.ViewViewComponentResult' to 'System.Threading.Tasks.Task' MVCStateManagement

所以我的问题是我应该采取什么方法?让异步忽略警告,或者是否有针对此警告的解决方法/修复?它对我的项目有那么大的影响吗?

谢谢!

您必须删除异步标志和 Task<>。就 return 个 IViewComponentResult.

当您进行异步工作时,您通常会 return 将一个对象包装到 Task<> 中。如果你不这样做就没有任何意义。

来自 MSDN:

The Task class represents a single operation that returns a value and that usually executes asynchronously. Task objects are one of the central components of the task-based asynchronous pattern first introduced in the .NET Framework 4. Because the work performed by a Task object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the Status property, as well as the IsCanceled, IsCompleted, and IsFaulted properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform.

https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1?view=netframework-4.7.2

编辑:

您也可以尝试 returning:

return Task.FromResult<IViewComponentResult>(View());

ViewcomponentResult 的任务上的方法运行s。 您可以使用以下命令在不异步的情况下调用它:

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

您的警告将不再显示,您的代码将 运行。 你也可以离开它。两者都不会影响您的项目的性能。

目前尚不清楚为什么该方法被定义为 async 方法,而 return 首先是 Task<IViewComponentResult>

由于该方法似乎是真正同步的并且只是 return 一个视图,您可能应该这样定义它:

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

同步方法不会因为您向其添加 async 关键字而神奇地变为异步。

如果您正在实现一个接口并且不能更改方法的签名,您可以使用 Task.FromResult 方法来 return 一个已经完成的任务(您仍然应该删除 async关键字):

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