Created
October 21, 2013 21:12
-
-
Save brenoferreira/7091089 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Async | |
{ | |
static IEnumerable<Uri> uris = new List<Uri>() | |
{ | |
new Uri("http://www.google.com"), | |
new Uri("http://www.bing.com"), | |
new Uri("http://www.yahoo.com") | |
}; | |
public static void DownloadStringAsync() | |
{ | |
var client = new WebClient(); | |
client.DownloadStringCompleted += (sender, e) => | |
{ | |
if (e.Error == null) | |
{ | |
Console.WriteLine(e.Result.Substring(0, 20)); | |
var client2 = new WebClient(); | |
client2.DownloadStringCompleted += (sender2, e2) => | |
{ | |
if (e2.Error == null) | |
{ | |
Console.WriteLine(e2.Result.Substring(0, 20)); | |
var client3 = new WebClient(); | |
client3.DownloadStringCompleted += (sender3, e3) => | |
{ | |
if (e3.Error == null) Console.WriteLine(e3.Result.Substring(0, 20)); | |
else Console.WriteLine(e3.Error.Message); | |
}; | |
client3.DownloadStringAsync(new Uri("http://www.yahoo.com")); | |
} | |
else Console.WriteLine(e2.Error.Message); | |
}; | |
client2.DownloadStringAsync(new Uri("http://www.bing.com")); | |
} | |
else Console.WriteLine(e.Error.Message); | |
}; | |
client.DownloadStringAsync(new Uri("http://www.google.com")); | |
} | |
public static void DownloadStringAsyncParallel() | |
{ | |
foreach (var uri in uris) | |
{ | |
var client = new WebClient(); | |
client.DownloadStringCompleted += (sender, e) => | |
{ | |
if (e.Error == null) Console.WriteLine(e.Result.Substring(0, 10)); | |
else Console.WriteLine(e.Error.Message); | |
}; | |
client.DownloadStringAsync(uri); | |
} | |
} | |
public static async void DownloadStringTaskAsync() | |
{ | |
var client = new WebClient(); | |
try | |
{ | |
Console.WriteLine(await client.DownloadStringTaskAsync("http://www.google.com")); | |
Console.WriteLine(await client.DownloadStringTaskAsync("http://www.bing.com")); | |
Console.WriteLine(await client.DownloadStringTaskAsync("http://www.yahoo.com")); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
} | |
public static async void DownloadStringTaskAsyncParallel() | |
{ | |
var client = new WebClient(); | |
try | |
{ | |
var htmls = await Task.WhenAll(uris.Select(uri => new WebClient().DownloadStringTaskAsync(uri))); | |
foreach (var html in htmls) | |
Console.WriteLine(html.Substring(0, 30)); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment