Skip to content

Instantly share code, notes, and snippets.

@MartinBodocky
Created September 29, 2014 13:14
Show Gist options
  • Save MartinBodocky/7d366c7d3834bdd0e396 to your computer and use it in GitHub Desktop.
Save MartinBodocky/7d366c7d3834bdd0e396 to your computer and use it in GitHub Desktop.
Play with async calls
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace AsyncTest
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Play with exception in asynchronous task");
MainAsync().Wait();
Console.WriteLine("Play with composing of asynchronous tasks");
List<string> urls = new List<string>
{
"http://www.google.com",
"http://www.altaine.com",
"http://www.microsoft.com"
};
Task<string[]> getUrls = GetPages(urls);
getUrls.Result.ToList().ForEach(p => Console.WriteLine("Page length: {0}", p.Length));
Console.WriteLine("I'm done now!");
Console.ReadLine();
}
static async Task<string[]> GetPages(List<string> urls)
{
var tasks = urls.Select(async url =>
{
using(var client = new HttpClient())
{
var res = await client.GetStringAsync(url);
Console.WriteLine("Downloading: {0}, Length: {1}",url, res.Length);
return res;
}
}).ToList();
return await Task.WhenAll(tasks);
}
static async Task MainAsync()
{
Console.WriteLine("MainAsync");
Task<string> task = ReadFileAsync("unknown place");
try
{
Console.WriteLine("MainAsync-try");
string text = await task;
Console.WriteLine("Text: {0}", text);
}
catch (Exception ex)
{
Console.WriteLine("Caught Exception: {0}", ex.Message);
}
}
private static async Task<string> ReadFileAsync(string filename)
{
Console.WriteLine("ReadFileAsync");
using(var reader = File.OpenText(filename))
{
return await reader.ReadToEndAsync();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment