SB2*_*055 3 .net c# apple-push-notifications async-await 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;
}
Run Code Online (Sandbox Code Playgroud)
我注意到它SendAppleNativeNotificationAsync是无限期挂起的(永远不会从包含方法返回),所以我试着告诉它在500ms后取消.但是仍然......对WhenAny现在的调用挂起并且我从未看到过return命中,导致消费者无限期地等待(这是调用此异步方法的同步方法,所以我调用.Wait()):
_commService.SendPushNotificationAsync(user.Username, notificationDto.PushContent).Wait(TimeSpan.FromSeconds(1));
Run Code Online (Sandbox Code Playgroud)
如何在一定时间后强制完成此操作,无论如何?
如果我只是"发射并忘记"而不是await执行任务会发生什么?
这是一个调用这个异步方法的同步方法,所以我调用.Wait()
那是你的问题.您正在陷入僵局,因为您正在阻止异步代码.
对此最好的解决方案是使用await而不是Wait:
await _commService.SendPushNotificationAsync(user.Username, notificationDto.PushContent);
Run Code Online (Sandbox Code Playgroud)
如果你绝对不能使用await,那么你可以尝试我的Brownfield Async文章中描述的其中一个黑客.
| 归档时间: |
|
| 查看次数: |
787 次 |
| 最近记录: |