Last active
December 16, 2015 11:29
-
-
Save huanlin/5428200 to your computer and use it in GitHub Desktop.
Download web contents asynchronously using Thread class.
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.Collections.Generic; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace Ex01_Console | |
{ | |
class ThreadDemo | |
{ | |
public static void Download(string[] urls) | |
{ | |
List<Thread> threads = new List<Thread>(); | |
foreach (string url in urls) | |
{ | |
Thread t = new Thread(Download); | |
threads.Add(t); | |
t.Start(url); | |
} | |
// 確保剛才建立的那些執行緒都執行完了之後才返回 Main() 函式. | |
threads.ForEach(t => t.Join()); | |
} | |
public static void Download(object url) | |
{ | |
using (var client = new System.Net.Http.HttpClient()) | |
{ | |
Task<string> task = client.GetStringAsync(url.ToString()); | |
string text = task.Result; | |
Console.WriteLine("Downloaded {0} chars from {1} on thread {2}", | |
text.Length, url, Thread.CurrentThread.ManagedThreadId); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment