我有一个具有以下抽象方法的基本控制器:
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()))); }更多推荐
忽略异步而不等待编译警告
发布评论