C#事件实现文件下载时进度提醒

C#中的事件是建立在委托的基础上,标准的事件模型应该包括以下几点:

  • 声明一个用于定义事件的委托,这里用系统自带的泛型委托原型EventHandler<TEventArgs>,如:public delegate void EventHandler<TEventArgs>(object sender,TEventArgs e);这里面的TEventArgs是由我们自定义的参数类型,继承自EventArgs基类
  • 事件参数的名称以EventArgs结束
  • 声明事件的委托原型即EventHandler,它的返回值为void
  • 声明事件的委托原型即EventHandler,它有两个参数:sender和e,sender表示事件触发者,e表示事件触发时的参数
  • 事件的声明是在普通委托声明的前面加上,event关键字,如:public event EventHandler<FileUploaderEventArgs> FileUploaded;
  • 因为委托可以在外面由调用者决定其变化,而事件是由所在的类型本身决定变化

文件下载时,要实时更新进度条,这时更新进度的方法就应该由下载类在下载的同时根据实时的下载进度利用事件去同步更新进度条的值,代码如下:

 1 namespace demo
 2 {
 3     public partial class Form1 : Form
 4     {
 5         public Form1()
 6         {
 7             InitializeComponent();
 8         }
 9 
10         private void button1_Click(object sender, EventArgs e)
11         {
12             FileUploader f1 = new FileUploader();
13             f1.FileUploaded += ShowProcess;                  //绑定事件
14             ThreadPool.QueueUserWorkItem((a) => f1.Upload());//加入线程池
15         }
16 
17         private void ShowProcess(object sender, FileUploaderEventArgs e)
18         {
19             //定义委托
20             Action t = () =>
21             {
22                 progressBar1.Value = e.FileProgress;
23                 label1.Text = e.FileProgress.ToString();
24             };
25 
26             //跨线程操作
27             this.BeginInvoke(t); 
28             Thread.Sleep(500);
29         }
30     }
31 
32     /// <summary>
33     /// 文件下载类
34     /// </summary>
35     class FileUploader
36     {
37         public event EventHandler<FileUploaderEventArgs> FileUploaded;//定义事件
38         public void Upload()
39         {
40             var e = new FileUploaderEventArgs() { FileProgress = 0 };
41             while (e.FileProgress < 100)
42             {
43                 e.FileProgress++;
44                 FileUploaded(this, e);//触发事件
45             }
46         }
47     }
48 
49     /// <summary>
50     /// 自定义参数
51     /// </summary>
52     class FileUploaderEventArgs : EventArgs
53     {
54         public int FileProgress { get; set; }
55     }
56 }

运行截图:

 

 

posted @ 2014-04-09 14:21  刘珍宝  阅读(1018)  评论(0编辑  收藏  举报