问题描述
我有以下代码:
public async Task SendPushNotificationAsync(string username, string message)
{
var task = ApnsNotifications.Instance.Hub.SendAppleNativeNotificationAsync(alert, username);
if (await Task.WhenAny(task, Task.Delay(500)) == task) {
return true;
}
return false;
}
我注意到SendAppleNativeNotificationAsync
无限期挂起(从不退出包含方法),因此我尝试告诉它在500毫秒后取消.但是仍然...对WhenAny
的调用现在挂起,我再也看不到return
被打,导致使用者无限期地等待(这是一个同步方法,调用此async方法,因此我调用.Wait()):
I noticed that SendAppleNativeNotificationAsync
was hanging indefinitely (never returning out of the containing method), so I tried telling it to cancel after 500ms. But still... the call to WhenAny
now hangs and I never see a return
get hit, resulting in the consumer just waiting indefinitely (it's a sync method calling this async method, so I call .Wait()):
_commService.SendPushNotificationAsync(user.Username, notificationDto.PushContent).Wait(TimeSpan.FromSeconds(1));
无论如何,我如何强制在设定的时间后完成此操作?
How do I force this to finish after a set time, no matter what?
如果我只是开枪而忘了",而不是await
执行任务,会发生什么?
What happens if I simply "fire and forget", instead of await
ing the Task?
推荐答案
那是你的问题.您死锁是因为您阻塞了异步代码.
对此的最佳解决方案是使用await
而不是Wait
:
The best solution for this is to use await
instead of Wait
:
await _commService.SendPushNotificationAsync(user.Username, notificationDto.PushContent);
如果您绝对不能使用await
,则可以尝试使用我的布朗菲尔德异步文章.
If you absolutely can't use await
, then you can try one of the hacks described in my Brownfield Async article.
这篇关于异步任务挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!