SB2055 SB2055 - 1 month ago 12
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
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?

What happens if I simply "fire and forget", instead of
await
ing the Task?

Answer

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.