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

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

问题描述

我有以下代码:

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 被命中,导致消费者无限期地等待(这是一个调用此异步方法的同步方法,所以我调用 .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?

推荐答案

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

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.

最好的解决方案是使用 await 而不是 Wait:

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

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

如果您绝对不能使用await,那么您可以尝试我的Brownfield 异步文章.

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

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

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