Apidcloud

DownloadStringAlternative

May 26th, 2016
56
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. internal static async Task<string> DownloadStringAsyncBugAlternative(string url, TimeSpan timeout)
  2.         {
  3.             try
  4.             {
  5.                 // create Http Client and dispose of it even if exceptions are thrown (same as using finally statement)
  6.                 using (var client = new HttpClient())
  7.                 {
  8.                     // should I always do this?
  9.                     client.CancelPendingRequests();
  10.  
  11.                     // store download task
  12.                     var downloadTask = client.GetAsync(new Uri(url));
  13.  
  14.                     // store delay task
  15.                     var timeoutTask = Task.Delay(timeout);
  16.  
  17.                     // await for both
  18.                     var completedTask = await Task.WhenAny(downloadTask, timeoutTask).ConfigureAwait(false);
  19.  
  20.                     // if timeout task was completed first
  21.                     if (completedTask == timeoutTask)
  22.                     {
  23.                         // throw timeout exception
  24.                         throw new HttpRequestException("The network request timed out. Please check your network connection.");
  25.                     }
  26.  
  27.                     // else, do download request and dispose of it when done
  28.                     using (var response = await downloadTask.ConfigureAwait(false))
  29.                     {
  30.                         // if response was successful
  31.                         if (response.IsSuccessStatusCode)
  32.                         {
  33.                             // return its content
  34.                             return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
  35.                         }
  36.                     }
  37.                 }
  38.             }
  39.             // Url Exceptions
  40.             catch (Exception ex) when (ex is ArgumentNullException || ex is UriFormatException)
  41.             {
  42.                 WriteLine("The Url provided isn't valid.");
  43.                 WriteLine(ex.Message);
  44.             }
  45.             // Cancelled task and timeout Exceptions
  46.             catch (Exception ex) when (ex is SocketException || ex is InvalidOperationException || ex is OperationCanceledException || ex is HttpRequestException || ex is System.IO.IOException)
  47.             {
  48.                 WriteLine("DownloadStringAsync task has been cancelled.");
  49.                 WriteLine(ex.Message);
  50.             }
  51.  
  52.             // return null if response was either unsuccessful or an exception was thrown
  53.             return null;
  54.         }
RAW Paste Data