问题
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:
Task.WhenAny(task, Task.Delay(500)) == task
is false. It means that the task timed outTask.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
andtask.Exception
to find more information
- If
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