SB2055 SB2055 - 1 year ago 118
C# Question

Async task hanging

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
was hanging indefinitely (never returning out of the containing method), so I tried telling it to cancel after 500ms. But still... the call to
now hangs and I never see a
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
ing the Task?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download