Capturing Exceptions on async operations

2020-03-13 06:13发布

问题:

I'm reading up more about async here: http://msdn.microsoft.com/en-us/library/hh873173(v=vs.110).aspx

Going through this example:

Task<bool> [] recommendations = …;
while(recommendations.Count > 0)
{ 
    Task<bool> recommendation = await Task.WhenAny(recommendations);    
    try
    {
        if (await recommendation) BuyStock(symbol);
        break;
    }
    catch(WebException exc)
    {
        recommendations.Remove(recommendation);
    }
}

I wonder, if I'm already performing await on Task.WhenAny why do I need to await again inside of the try block?

If I already did this: Task<bool> recommendation = await Task.WhenAny(recommendations); Why do this: if (await recommendation) BuyStock(symbol);

回答1:

The first await exists to asynchronously wait for the first task to complete (i.e. recommendation). The second await is only there to extract the actual result out of the already completed task, and throw exceptions stored in the task. (it's important to remember that awaiting a completed task is optimized and will execute synchronously).

A different option to get the result would be using Task<T>.Result, however it differs in the way it handles exceptions. await would throw the actual exception (e.g WebException) while Task<T>.Result would throw an AggregateException containing the actual exception inside.

Task<bool> [] recommendations = …;
while(recommendations.Count > 0)
{ 
    Task<bool> recommendation = await Task.WhenAny(recommendations);    
    try
    {
        if (recommendation.Result) 
        {
            BuyStock(symbol);
        }
        break;
    }
    catch(AggregateException exc)
    {
        exc = exc.Flatten();
        if (exc.InnerExceptions[0] is WebException)
        {
            recommendations.Remove(recommendation);
        }
        else
        {
            throw;
        }
    }
}

Clearly awaiting the task is simpler and so it's the recommended way of retrieving a result out of a task.



回答2:

The use of await here creates the desired error handling semantics. If he used Result instead of await then the AggregateException would be rethrown directly; when using await the first exception within the AggregateException is pulled out an that exception is re-thrown. Clear the author of this code wanted the WebException to be thrown, rather than an AggregateException that he would need to manually unwrap.

Could he have used another approach, sure. This was simply the approach that the author of the code preferred, as it allows him to write the code more like traditional synchronous code rather than radically changing the style of the code.



回答3:

You're right. It is not necessary. You could replace it with

if (recommendation.Result) 
    BuyStock(symbol);

Also note that await will not await(will not set continuation) when completed task is given. It will just execute synchronously in that case as a optimization. I guess author leverages that optimization.

If you ask why author wrote that way, May be consistency? only he knows!.



回答4:

If I already did this: Task recommendation = await Task.WhenAny(recommendations); Why do this: if (await recommendation) BuyStock(symbol);

Because Task.WhenAny returns a Task<Task<bool>> and you want to unwrap the outter Task to retrieve the resulting bool. You could do the same by accessing the Task.Result property of the returned Task



回答5:

Other answers have pointed out that you have to await the task returned by await Task.WhenAll to unwrap the return value (alternatively, you can use the Result property).

However, you can also get rid of your try/catch (and it's a good thing to avoid catching unnecessary exception)

Task<bool> recommendation = await Task.WhenAny(recommendations);    
if(!recommendation.IsFaulted)
{
    if (await recommendation) BuyStock(symbol);
    break;
}
else
{
    if(recommendation.Exception.InnerExceptions[0] is WebException)
    {
        recommendations.Remove(recommendation);
    }
    else
    {
        throw recommendation.Exception.InnerExceptions[0];
    }
}


回答6:

Because Task.WhenAny<TResult>(IEnumerable<Task<TResult>> tasks) returns a Task<Task<TResult>>. The outer task (the one created by the Task.WhenAny call) will complete when any of the tasks passed to it completes with the completed task as a result.