异步任务挂起 [英] Async task hanging

查看:73
本文介绍了异步任务挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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 awaiting the Task?

推荐答案

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

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

那是你的问题.您死锁是因为您阻塞了异步代码.

对此的最佳解决方案是使用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.

这篇关于异步任务挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆