如何捕获AggregateException?

时间:2017-07-05 00:47:12

标签: c# asynchronous task

我有一个简单的程序,但我不确定为什么我没有在调用者中捕获AggregateException或只是Exception?以下代码行:var webRequest = WebRequest.Create(url);将抛出无效的url异常。但是调用者代码中没有捕获异常。任何人都可以告诉我为什么在这种情况下我没有捕获AggregateException吗?

class Program
{
    static void GetWebResponseSizeAsync(string url)
    {
        var webRequest = WebRequest.Create(url);

        var webResponse = webRequest.GetResponse();

        using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
        {
            string text = streamReader.ReadToEnd();

            Console.WriteLine("Read {0} bytes from web site {1}", text.Length, url);
        }
    }
    static void Main(string[] args)
    {
        string url = @"www.google.com";

        try
        {
            var task = Task.Run(()=>GetWebResponseSizeAsync(url));

            Console.WriteLine("....");
        }
        catch (AggregateException e)
        {
            Console.WriteLine("Catch exception: {0}", e.Message);
        }

        Console.WriteLine("Done");

        Console.ReadLine();
    }
}

0 个答案:

没有答案