Skip to content

Instantly share code, notes, and snippets.

@edward-hsu-1994
Last active August 29, 2015 14:17
Show Gist options
  • Save edward-hsu-1994/5b661d39ea0c6fb2d9da to your computer and use it in GitHub Desktop.
Save edward-hsu-1994/5b661d39ea0c6fb2d9da to your computer and use it in GitHub Desktop.
C# yield download callback
//Xu Pei Yao - 2015/03/23 - 22:35
class Program {
static void DownloadHtml(string url,out string html,ref int time) {
string result = new WebClient().DownloadString(url);
lock(result) {
time--;
html = result;
if(time == 0)th.MoveNext();//跳脫點繼續
}
}
static IEnumerable DownloadPages(params string[] urls) {//迭代器
string[] HtmlAry = new string[urls.Length];
Thread[] DownloadThreads = new Thread[urls.Length];
int time = urls.Length;//計數器
for(int i = 0 ; i < urls.Length;i++) {
DownloadThreads[i] = new Thread((obj) => {
DownloadHtml(urls[(int)obj] ,out HtmlAry[(int)obj] ,ref time);
});
}
for(int i = 0 ; i < urls.Length;i++){
DownloadThreads[i].Start(i);
}
yield return null;//跳脫
foreach(string html in HtmlAry)
Console.WriteLine(html.Length);
}
static IEnumerator th;//迭代器
static void Main(string[] args) {
Console.WriteLine("Main START");
th = DownloadPages(//同時下載以下頁面,完成後顯示所有頁面的長度
"http://www.google.com.tw/",
"http://www.yahoo.com.tw/",
"http://www.nkfust.edu.tw/"
).GetEnumerator();
th.MoveNext();
Console.WriteLine("Main End");
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment