Skip to content

Instantly share code, notes, and snippets.

@jamesmanning
Created March 4, 2012 18:25
Show Gist options
  • Save jamesmanning/1974278 to your computer and use it in GitHub Desktop.
Save jamesmanning/1974278 to your computer and use it in GitHub Desktop.
async Task, foreach and list, waits
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
namespace ItsBigItsHeavyItsWood
{
class Program
{
static void Main()
{
var urlsToDownload = new[]
{
"http://www.google.com/",
"http://www.microsoft.com/",
"http://www.apple.com/",
};
var allDownloadTasks = new List<Task>();
foreach (var url in urlsToDownload)
{
var thisDownloadTask = DownloadUrl(url);
allDownloadTasks.Add(thisDownloadTask);
}
Task.WaitAll(allDownloadTasks.ToArray());
}
private static async Task DownloadUrl(string url)
{
var client = new HttpClient();
Console.WriteLine("Starting to download url {0}", url);
var contents = await client.GetByteArrayAsync(url);
Console.WriteLine("Downloaded {0} bytes", contents.Length);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment