今天学习的线程,并用多线程实现了一个简单的下载网页的案例,如下:
前台设计入下:两个Button,一个TextBox和一个 backgroundworker控件
后台代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 30320; i < 30340; i++)
{
try
{
WebClient client = new WebClient();
client.DownloadFile(@"http://job.cnblogs.com/offer/" + i + "/", @"E:\PPDownload\" + i + ".html");
}
catch (Exception ex)//异常吃掉
{ }
}
Action action = new Action(Msg);
this.Invoke(action);
}
private void Msg()
{
MessageBox.Show("下载成功");
}
private void button1_Click(object sender, EventArgs e)
{
this.backgroundWorker1.RunWorkerAsync();
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("精彩大片,应有尽有");
}
}
}
点击下载按钮程序运行时,点击资源库按钮是可以运行的,这就是开辟了另外一个线程的元婴;下载完成后需要点击弹出的会话框"下载完成",再次点击资源库按钮可以运行,若不点击“下载完成”,资源库按钮不会被执行。