public
anonymous / gist:4478284
Created

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
async private void Download_Click_1(object sender, RoutedEventArgs e)
{
string[] files =
{
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg",
"https://si0.twimg.com/profile_images/523560950/discount_1__bigger.jpg"
};
 
List<Task<Byte[]>> tasks = new List<Task<Byte[]>>();
for (int idx = 0; idx < files.Count(); idx++)
{
var file = files[idx];
 
var taskStart = DownloadImageData(new Uri(file), null);
tasks.Add(taskStart);
 
if (((idx > 0) && (idx % 5 == 0)) || (idx == files.Count() - 1))
{
await Task.WhenAll(tasks);
tasks.Clear();
}
}
}
 
private async Task<Byte[]> DownloadImageData(Uri url, Object userState)
{
Byte[] contentBytes = null;
 
using (HttpClientHandler _handler = new HttpClientHandler())
{
_handler.AllowAutoRedirect = true;
_handler.MaxAutomaticRedirections = 4;
 
using (HttpClient httpClient = new HttpClient(_handler))
{
httpClient.DefaultRequestHeaders.ExpectContinue = false;
httpClient.DefaultRequestHeaders.Add("Keep-Alive", "false");
 
try
{
// Exception IS THROWN AT LINE BELOW
contentBytes = await httpClient.GetByteArrayAsync(url.OriginalString);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Download Failed :" + ex.Message);
throw ex;
}
}
 
_handler.Dispose();
}
 
return contentBytes;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.