异步任务挂起

时间:2016-11-01 16:05:58

标签: c# .net async-await apple-push-notifications azure-notificationhub

我有以下代码:

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无限期挂起(永远不会从包含方法返回),所以我试着告诉它在500ms后取消。但仍然......对WhenAny的调用现在挂起,我从未看到return被点击,导致消费者无限期地等待(这是一个调用此异步方法的同步方法,所以我打电话.Wait ()):

_commService.SendPushNotificationAsync(user.Username, notificationDto.PushContent).Wait(TimeSpan.FromSeconds(1));

如何在一段时间后强制完成此操作,无论如何?

如果我只是“发射并忘记”,而不是await任务,会发生什么?

1 个答案:

答案 0 :(得分:5)

  

这是一个调用此异步方法的同步方法,所以我调用.Wait()

这就是你的问题。你是deadlocking because you're blocking on asynchronous code

最佳解决方案是使用await代替Wait

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

如果您绝对不能使用await,那么您可以尝试我Brownfield Async article中描述的其中一个黑客。

相关问题