Consider Using async without await.
think that maybe you misunderstand what async does. The warning is exactly right: if you mark your method async but don't use await anywhere, then your method won't be asynchronous. If you call it, all the code inside the method will execute synchronously.
I want write a method that should run async but don't need use await.for example when use a thread
public async Task PushCallAsync(CallNotificationInfo callNotificationInfo)
{
Logger.LogInfo("Pushing new call {0} with {1} id".Fill(callNotificationInfo.CallerId,
}
I want call PushCallAsync
and run async and don't want use await.
Can I use async without await in C#?
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 anasync
method as it does eventually call File.WriteAsync() or so.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. ThenLogger.LogInfo(..)
will usually return aTask
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):or
If Logger.LogInfo is a synchronous method, the whole call will be synchronous anyway. If all you want to do is to execute the code in a separate thread, async is not the tool for the job. Try with thread pool instead:
You still are misunderstanding
async
. Theasync
keyword does not mean "run on another thread".To push some code onto another thread, you need to do it explicitly, e.g.,
Task.Run
:I have an
async
/await
intro post that you may find helpful.If your
Logger.LogInfo
is already async this is enough:If it is not just start it async without waiting for it