Async task hanging [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-10 18:52:50

问题


I have the following code:

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;
}

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?

What happens if I simply "fire and forget", instead of awaiting the Task?


回答1:


it's a sync method calling this async method, so I call .Wait()

And that's your problem. You're deadlocking because you're blocking on asynchronous code.

The best solution for this is to use await instead of Wait:

await _commService.SendPushNotificationAsync(user.Username, notificationDto.PushContent);

If you absolutely can't use await, then you can try one of the hacks described in my Brownfield Async article.



来源:https://stackoverflow.com/questions/40363918/async-task-hanging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!