在没有等待的情况下使用异步? [英] Using async without await?
问题描述
考虑使用异步而不等待.
认为您可能误解了 async 的作用.警告是完全正确:如果您将方法标记为异步但不使用等待任何地方,那么你的方法就不会是异步的.如果你调用它,所有方法内的代码会同步执行.
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,
}
我想调用 PushCallAsync
并运行异步,不想使用 await.
I want call PushCallAsync
and run async and don't want use await.
我可以在 C# 中使用 async 而不使用 await 吗?
Can I use async without await in C#?
推荐答案
如果你的 Logger.LogInfo
已经是异步的,这就足够了:
If your Logger.LogInfo
is already async this is enough:
public void PushCallAsync(CallNotificationInfo callNotificationInfo)
{
Logger.LogInfo("Pushing new call {0} with {1} id".Fill(callNotificationInfo.CallerId,
}
如果不是不等待就异步启动
If it is not just start it async without waiting for it
public void PushCallAsync(CallNotificationInfo callNotificationInfo)
{
Task.Run(() => Logger.LogInfo("Pushing new call {0} with {1} id".Fill(callNotificationInfo.CallerId));
}
这篇关于在没有等待的情况下使用异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!