Debugging Task.WhenAny and Push Notifications

落爺英雄遲暮 提交于 2019-12-11 07:12:42

问题


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.


回答1:


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);



回答2:


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).



来源:https://stackoverflow.com/questions/43170246/debugging-task-whenany-and-push-notifications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!