您的位置:首页 > 其它

loner_li windows 多线程实例 文件下载、面积计算、多线程下载等

2013-07-02 09:21 267 查看


详细代码:
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) { }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: