Ignore async without await compilation warning

后端 未结 2 1891
星月不相逢
星月不相逢 2021-02-10 11:19

I have a base controller with the following abstract method:

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

In one

2条回答
  •  孤独总比滥情好
    2021-02-10 11:41

    While Yuval's answer regarding removing the async completely is usually the prefered way to remove the warning, another correct answer that doesn't degrage performance is to await an already completed task.

    await is roughly translated to checking whether the awaited task completed, if so continue on executing the rest of the method synchronously and if not add the rest as a continuation on that task.

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

    In .Net 4.6 you can use the new Task.CompletedTask property instead of creating your own completed task.

    This enables you to keep the method async and with it keep the same error-handling semantics.

提交回复
热议问题