忽略异步而不等待编译警告

Ignore async without await compilation warning

我有一个具有以下抽象方法的基本控制器:

[HttpDelete]
public abstract Task<IHttpActionResult> Delete(int id);

在一个特定的控制器中,我不想实现删除,所以该方法如下所示:

public override async Task<IHttpActionResult> Delete(int id)
{
    return ResponseMessage(Request.CreateResponse(HttpStatusCode.MethodNotAllowed, new NotSupportedException()));
}

虽然上面的代码可以编译,但我收到警告:

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.

除了忽略上述警告之外,是否有更好的替代方法(即更改上面的代码)来避免出现此警告?

编辑

我将行更改为:

return await Task.Run(() => ResponseMessage(Request.CreateResponse(HttpStatusCode.MethodNotAllowed, new NotSupportedException())));

这将删除警告。但是,有更好的解决方案吗?

Apart from ignoring the above warning, is there a better alternative (ie. changing the code above) so that this warning doesn't occur?

另一种方法是删除 async 修饰符并使用 Task.FromResult 到 return a Task<IHttpActionResult>:

public override Task<IHttpActionResult> Delete(int id)
{
    return Task.FromResult<IHttpActionResult>(
                ResponseMessage(Request.CreateResponse(
                                        HttpStatusCode.MethodNotAllowed,
                                        new NotSupportedException())));
}

虽然 关于完全删除 async 通常是删除警告的首选方法,但另一个 correct 不会降低性能的答案是await 一个已经完成的任务。

await 大致翻译为检查等待的任务是否完成,如果完成则继续同步执行方法的其余部分,如果未完成则将其余部分添加为该任务的延续。

private static readonly Task _completedTask = Task.FromResult(false);
public override async Task<IHttpActionResult> Delete(int id)
{
    await _completedTask;
    return ResponseMessage(Request.CreateResponse(HttpStatusCode.MethodNotAllowed, new NotSupportedException()));
}

在 .Net 4.6 中,您可以使用新的 Task.CompletedTask 属性 而不是创建您自己的已完成任务。

这使您能够保留方法 async 并随之保留 same error-handling semantics.