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

编程入门 行业动态 更新时间:2024-10-26 14:26:50
本文介绍了忽略异步而不等待编译警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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()))); }

更多推荐

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

本文发布于:2023-11-23 10:22:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621099.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!