Skip to content

Instantly share code, notes, and snippets.

@ridercz
Created January 26, 2018 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ridercz/8b7e2df324249d92797c185de25eaf9d to your computer and use it in GitHub Desktop.
Save ridercz/8b7e2df324249d92797c185de25eaf9d to your computer and use it in GitHub Desktop.
Sync/Parallel/Async file download
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace Downloads {
class Program {
static void Main(string[] args) {
var urls = new string[] {
"https://www.aspnet.cz/",
"https://www.rider.cz/",
"https://www.vlcak.cz/",
"https://www.wolfcult.cz/"
};
// Sync
Console.WriteLine("Downloading synchronously:");
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
foreach (var url in urls) {
DownloadUrl(url);
}
sw.Stop();
Console.WriteLine($"Done in {sw.ElapsedMilliseconds} ms");
// Parallel
Console.WriteLine("Downloading parallel:");
sw.Restart();
Parallel.ForEach(urls, url => {
DownloadUrl(url);
});
sw.Stop();
Console.WriteLine($"Done in {sw.ElapsedMilliseconds} ms");
// Async
Console.WriteLine("Downloading async:");
sw.Restart();
var tasks = urls.Select(url => DownloadUrlAsync(url)).ToArray();
Task.WaitAll(tasks);
sw.Stop();
Console.WriteLine($"Done in {sw.ElapsedMilliseconds} ms");
}
public static async Task DownloadUrlAsync(string url) {
using (var wc = new WebClient()) {
Console.WriteLine($" Started {url}...");
var s = await wc.DownloadDataTaskAsync(url);
Console.WriteLine($" Finished {url}, {s.Length} bytes...");
}
}
public static void DownloadUrl(string url) {
using (var wc = new WebClient()) {
Console.WriteLine($" Started {url}...");
var s = wc.DownloadData(url);
Console.WriteLine($" Finished {url}, {s.Length} bytes...");
}
}
}
}
@PhenomAmd
Copy link

How to handle completion?? I mean

wc->DownloadFile(url,path+"name.exe");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment