详细代码:
private void button1_Click(object sender, EventArgs e)
{
ThreadStart start = new ThreadStart(DownLoad);
Thread thread = new Thread(start);
thread.Start();
//MessageBox.Show("下载完成");
}
private void Mianji(object r)
{
double result = Math.PI * Convert.ToInt32(r) * Convert.ToInt32(r);
this.Invoke(new Action(delegate()
{
MessageBox.Show(result.ToString());
}));
}
private void DownLoad()
{
for (int i = 30000; i < 30010; i++)
{
try
{
using (WebClient client = new WebClient())
{
client.DownloadFile(@"http://job.cnblogs.com/offer/" + i + "/", @"e:\movices\" + i + ".html");
//使用匿名委托的简写方式
this.Invoke(new Action(delegate()
{
this.textBox1.AppendText("第" + i + "个帖子已经下载完成\n");
}));
}
}
catch (Exception ex) { }
}
Action action = new Action(Msg);
this.Invoke(action);
}
private void Msg()
{
MessageBox.Show("下载完成");
}
private void button2_Click(object sender, EventArgs e)
{
ParameterizedThreadStart start = new ParameterizedThreadStart(Mianji);
Thread thread = new Thread(start);
thread.Start(5);
}
//使用线程池下载帖子
private void button3_Click(object sender, EventArgs e)
{
//这么写其实只是让线程池启动了一个线程,没有利用多线程来操作
WaitCallback wait = new WaitCallback(DownLoadThreadPool);
ThreadPool.QueueUserWorkItem(wait);
}
private void DownLoadThreadPool(object obj)
{
for (int i = 30000; i < 30010; i++)
{
try
{
using (WebClient client = new WebClient())
{
client.DownloadFile(@"http://job.cnblogs.com/offer/" + i + "/", @"e:\movices\" + i + ".html");
//使用匿名委托的简写方式
this.Invoke(new Action(delegate()
{
this.textBox1.AppendText("第" + i + "个帖子已经下载完成\n");
}));
}
}
catch (Exception ex) { }
}
Action action = new Action(Msg);
this.Invoke(action);
}
//线程池多线程下载
private void button4_Click(object sender, EventArgs e)
{
for (int i = 30000; i < 30020; i++)
{
WaitCallback wait=new WaitCallback(DownLoadThreadPool2);
ThreadPool.QueueUserWorkItem(wait, i);
}
}
private void DownLoadThreadPool2(object obj)
{
try
{
using (WebClient client = new WebClient())
{
client.DownloadFile(@"http://job.cnblogs.com/offer/" + Convert.ToInt32(obj) + "/", @"e:\movices\" + Convert.ToInt32(obj) + ".html");
//使用匿名委托的简写方式
this.Invoke(new Action(delegate()
{
this.textBox1.AppendText("第" + Convert.ToInt32(obj) + "个帖子已经下载完成\n");
}));
}
}
catch (Exception ex) { }
}