Created
November 6, 2011 21:52
-
-
Save brenoferreira/1343587 to your computer and use it in GitHub Desktop.
C# Async
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
using System; | |
using System.Linq; | |
using System.Net; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace Blog_CSharpAsync | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
PrintBingHomePageHTMLAsync(); | |
Console.ReadKey(); | |
PrintFromOneToThenThenFromElevenToTwentyUsingTasks(); | |
Console.ReadKey(); | |
PrintFromOneToThenThenFromElevenToTwentyAsync(); | |
Console.ReadKey(); | |
} | |
private static async void PrintBingHomePageHTMLAsync() | |
{ | |
var bingHomePageHTML = await DownloadBingHomePageHTMLAsync(); | |
Console.WriteLine(bingHomePageHTML); | |
} | |
private static async Task<String> DownloadBingHomePageHTMLAsync() | |
{ | |
var webClient = new WebClient(); | |
var html = await webClient.DownloadStringTaskAsync("http://www.bing.com"); | |
return html; | |
} | |
private static void PrintFromOneToThenThenFromElevenToTwentyUsingTasks() | |
{ | |
var task = new Task(() => | |
Enumerable.Range(1, 10).ToList().ForEach(i => | |
{ | |
Thread.Sleep(10); | |
Console.WriteLine(i); | |
}) | |
); | |
task.GetAwaiter().OnCompleted(() => | |
Enumerable.Range(11, 10).ToList().ForEach(i => | |
{ | |
Thread.Sleep(10); | |
Console.WriteLine(i); | |
}) | |
); | |
task.Start(); | |
task.Wait(); | |
} | |
private static async Task PrintFromOneToThenThenFromElevenToTwentyAsync() | |
{ | |
await PrintFromOneToTenAsync(); | |
Enumerable.Range(11, 10).ToList().ForEach(i => Console.WriteLine(i)); | |
return; | |
} | |
private static async Task PrintFromOneToTenAsync() | |
{ | |
var task = new Task(() => | |
Enumerable.Range(1, 10).ToList().ForEach(i => | |
{ | |
Thread.Sleep(10); | |
Console.WriteLine(i); | |
}) | |
); | |
task.Start(); | |
await task; | |
return; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ty