Is it OK to declare an async method as returning void to silence the CS4014 warning?

前端 未结 4 1898
南方客
南方客 2021-01-02 03:12

Visual Studio emits a warning for this code (\'because this call is not awaited, execution of the current method continues before the call is completed\').

s         


        
4条回答
  •  伪装坚强ぢ
    2021-01-02 03:37

    Sometimes you want to fire and forget, however you should always want to make it explicit for someone reading your code. I find the "_" notation not explicit enough, so here's how I do it, with an extension method:

    public static class TaskExtensions()
    {
        public static void InvokeAndIgnore(this Task fireAndForgetTask)
        {
            // deliberately do nothing; used to suppress warning
        }
    }
    

    You can use it as follows:

    worker.AttemptCloseAsync().InvokeAndIgnore();
    

提交回复
热议问题