gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:22:14 24 4
gpt4 key购买 nike

我有一个具有以下抽象方法的基本 Controller :

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

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

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返回 Task<IHttpActionResult> :

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

关于c# - 忽略异步而不等待编译警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30501120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com