简体   繁体   中英

Debugging Task.WhenAny and Push Notifications

I have the following snippet to handle Azure Notification Hub push notifications:

var alert = "{\"aps\":{\"alert\":\"" + message + "\"}}";

var task = AzurePushNotifications.Instance.Hub.SendAppleNativeNotificationAsync(alert, username);

if (await Task.WhenAny(task, Task.Delay(500)) == task)
{
     success = true;
}

Occasionally, this will fail - I'm trying to figure out why ?

What's the best way to get some diagnostic information when running things with Task.WhenAny ?

I'd like to know if either an exception was thrown, or if the timeout has been hit.

You basically have three possibilities:

  1. Task.WhenAny(task, Task.Delay(500)) == task is false. It means that the task timed out
  2. Task.WhenAny(task, Task.Delay(500)) == task is true. Then either:
    • If t1.Status == TaskStatus.RanToCompletion , then the task ran successfully
    • Otherwise, it's either cancelled or faulted. Check task.IsFaulted and task.Exception to find more information

If it takes > 500ms, I want it to fail, but I want to know that's why it failed

In that case, the only thing you can know is that the notification timed out. There is no exception to log since the task hasn't completed yet. If you want to check the status when it eventually completes, you can chain a continuation:

task.ContinueWith(t => 
{
    // Log t.Exception
}, TaskContinuationOptions.OnlyOnFaulted);

I'd like to know if either an exception was thrown, or if the timeout has been hit.

You just need to observe the completed task, as such:

var task = ...;
if (await Task.WhenAny(task, Task.Delay(500)) == task)
{
  await task;
  success = true;
}

This will propagate the exception, allowing you to distinguish between the task failing (an exception will be thrown), the task succeeding ( success == true ), and the task timing out ( success == false ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM