Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- internal static async Task<string> DownloadStringAsyncBugAlternative(string url, TimeSpan timeout)
- {
- try
- {
- // create Http Client and dispose of it even if exceptions are thrown (same as using finally statement)
- using (var client = new HttpClient())
- {
- // should I always do this?
- client.CancelPendingRequests();
- // store download task
- var downloadTask = client.GetAsync(new Uri(url));
- // store delay task
- var timeoutTask = Task.Delay(timeout);
- // await for both
- var completedTask = await Task.WhenAny(downloadTask, timeoutTask).ConfigureAwait(false);
- // if timeout task was completed first
- if (completedTask == timeoutTask)
- {
- // throw timeout exception
- throw new HttpRequestException("The network request timed out. Please check your network connection.");
- }
- // else, do download request and dispose of it when done
- using (var response = await downloadTask.ConfigureAwait(false))
- {
- // if response was successful
- if (response.IsSuccessStatusCode)
- {
- // return its content
- return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
- }
- }
- }
- }
- // Url Exceptions
- catch (Exception ex) when (ex is ArgumentNullException || ex is UriFormatException)
- {
- WriteLine("The Url provided isn't valid.");
- WriteLine(ex.Message);
- }
- // Cancelled task and timeout Exceptions
- catch (Exception ex) when (ex is SocketException || ex is InvalidOperationException || ex is OperationCanceledException || ex is HttpRequestException || ex is System.IO.IOException)
- {
- WriteLine("DownloadStringAsync task has been cancelled.");
- WriteLine(ex.Message);
- }
- // return null if response was either unsuccessful or an exception was thrown
- return null;
- }
Add Comment
Please, Sign In to add comment