Created
January 26, 2018 10:08
-
-
Save ridercz/8b7e2df324249d92797c185de25eaf9d to your computer and use it in GitHub Desktop.
Sync/Parallel/Async file download
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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..."); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to handle completion?? I mean
wc->DownloadFile(url,path+"name.exe");