Using async without await in C#?

前端 未结 4 976
别那么骄傲
别那么骄傲 2020-12-05 04:43

Consider Using async without await.

think that maybe you misunderstand what async does. The warning is exactly right: if you mark your method async

4条回答
  •  爱一瞬间的悲伤
    2020-12-05 04:59

    You're misunderstanding async. It actually just tells the Compiler to propagate the inversion of control flow it does in the background for you. So that the whole method stack is marked as async.

    What you actually want to do depends on your problem. (Let's consider your call Logger.LogInfo(..) is an async method as it does eventually call File.WriteAsync() or so.

    • If you calling function is a void event handler, you're good. The async call will happen to some degree (namely File.WriteAsync) in the background. You do not expect any result in your control flow. That is fire and forget.
    • If however you want to do anything with the result or if you want to continue only then, when Logger.LogInfo(..) is done, you have to do precautions. This is the case when your method is somehow in the middle of the call-stack. Then Logger.LogInfo(..) will usually return a Task and that you can wait on. But beware of calling task.Wait() because it will dead lock your GUI-Thread. Instead use await or return the Task (then you can omit async):

    public void PushCallAsync(CallNotificationInfo callNotificationInfo) 
    {
       return Logger.LogInfo("Pushing new call {0} with {1} id".Fill(callNotificationInfo.CallerId); 
    }

    or

     public async void PushCallAsync(CallNotificationInfo callNotificationInfo) 
     {
        await Logger.LogInfo("Pushing new call {0} with {1} id".Fill(callNotificationInfo.CallerId); 
     }
    

提交回复
热议问题