using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Errors
{
    class Examples20_22
    {
        // Listing 18-20
        static async Task CatchAll(Task[] ts)
        {
            try
            {
                var t = Task.WhenAll(ts);
                await t.ContinueWith(
                            x => { },
                            TaskContinuationOptions.ExecuteSynchronously);
                t.Wait();
            }
            catch (AggregateException all)
            {
                Console.WriteLine(all);
            }
        }

        // Klasa zagnieżdżona użyta w celu uniknięcia konfliktu nazw
        class Nested
        {
            // Listing 18-21
            static async Task CatchAll(Task[] ts)
            {
                Task t = null;
                try
                {
                    t = Task.WhenAll(ts);
                    await t;
                }
                catch (Exception first)
                {
                    Console.WriteLine(first);

                    if (t != null && t.Exception.InnerExceptions.Count > 1)
                    {
                        Console.WriteLine("Znaleziono więcej wyjątków:");
                        Console.WriteLine(t.Exception);
                    }
                }
            }
        }

        // Listing 18-22
        static async Task GetSeveral()
        {
            using (var w = new HttpClient())
            {
                w.MaxResponseContentBufferSize = 2000000;

                Task<string> g1 = w.GetStringAsync("http://helion.pl/");
                Task<string> g2 =
                    w.GetStringAsync("http://helion.pl/kategorie/programowanie/c-sharp");

                // BŁĄD!
                Console.WriteLine((await g1).Length);
                Console.WriteLine((await g2).Length);
            }
        }
    }
}
