忽略异步而不等待编译警告 [英] Ignore async without await compilation warning

查看:95
本文介绍了忽略异步而不等待编译警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a base controller with the following abstract method:

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

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

In one particular controller, I don't want to implement deletion, so the method looks like this:

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

尽管上面的代码可以编译,但我得到警告:

Although the above code compiles, I get a warning:

此异步方法缺少等待"运算符,将同步运行.考虑使用"await"运算符来等待非阻塞API调用,或者使用"await Task.Run(...)"来在后台线程上执行CPU绑定的工作.

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.

除了忽略以上警告之外,还有没有更好的选择(即更改上面的代码),这样就不会发生此警告?

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

编辑

我将行更改为:

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

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

This removes the warning. However, is there a better solution?

推荐答案

除了忽略以上警告之外,还有没有更好的选择(即更改上面的代码),以便不会发生此警告?

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> :

The alternative is to remove the async modifier and use Task.FromResult to return a Task<IHttpActionResult>:

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

这篇关于忽略异步而不等待编译警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆