Awaiting Failed Operations - CSharp Thread Asynchronous

CSharp examples for Thread Asynchronous:Async

Description

Awaiting Failed Operations

Demo Code

using System;//w  w w.j  ava  2  s.co  m
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http;
using System.Threading.Tasks;
class AwaitingFailedOperations
{
   static void Main()
   {
      var task = FetchFirstSuccessfulAsync(new[] {
         "http://book2s.com",
         "http://apress.com",
         "https://manning.com",
         "https://microsoft.com"
      });
      var result = task.GetAwaiter().GetResult();
      Console.WriteLine(result.Length);
   }
   static async Task<string> FetchFirstSuccessfulAsync(IEnumerable<string> urls)
   {
      var client = new HttpClient();
      foreach (string url in urls)
      {
         try
         {
            return await client.GetStringAsync(url);
         }
         catch (HttpRequestException exception)
         {
            Console.WriteLine("Failed to fetch {0}: {1}", url, exception.Message);
         }
      }
      throw new HttpRequestException("No URLs succeeded");
   }
}

Related Tutorials