Capturing Exceptions on async operations

前端 未结 6 1139
滥情空心
滥情空心 2021-01-12 01:00

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 [         


        
6条回答
  •  日久生厌
    2021-01-12 01:41

    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.Result, however it differs in the way it handles exceptions. await would throw the actual exception (e.g WebException) while Task.Result would throw an AggregateException containing the actual exception inside.

    Task [] recommendations = …;
    while(recommendations.Count > 0)
    { 
        Task 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.

提交回复
热议问题