Capturing Exceptions on async operations

梦想与她 提交于 2020-01-29 11:50:10

问题


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.



来源:https://stackoverflow.com/questions/25624315/capturing-exceptions-on-async-operations

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