Debug Task.WhenAny and Push Notifications

I have the following snippet for handling Azure Notification Hub notification 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;
}

      

Sometimes it will fail - I'm trying to figure out why?

What's the best way to get diagnostic information while working with Task.WhenAny

?

I would like to know if any exception was thrown or if the timeout was hit.

+1


source to share


2 answers


Basically, you have three possibilities:

  • Task.WhenAny(task, Task.Delay(500)) == task

    - false. This means that the waiting time for the task
  • Task.WhenAny(task, Task.Delay(500)) == task

    true. Then either:
    • If t1.Status == TaskStatus.RanToCompletion

      , then the task is completed successfully
    • Otherwise, it is canceled or canceled. Check task.IsFaulted

      and task.Exception

      to find more information

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



In this case, the only thing you can know is that the notification has been disabled. There is no log exception because the task has not yet completed. If you want to check the status when it eventually completes, you can chain the continuation:

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

      

+1


source


I would like to know if any exception was thrown or if the timeout was removed.

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



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

      

This will propagate an exception to differentiate between task failure (an exception is thrown), the task being executed ( success == true

), and the task timeout ( success == false

).

+1


source







All Articles