码迷,mamicode.com
首页 > Windows程序 > 详细

BackgroundWorker实现的winfrom中实现异步等待加载图片显示

时间:2015-08-07 14:37:04      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

BackgroundWorker简介

   BackgroundWorker在winfrom中有对应控件,该有三个事件:DoWork 、ProgressChanged 和 RunWorkerCompleted。

在程序中调用RunWorkerAsync方法则会启动DoWork事件的事件处理,当在事件处理过程中,调用 ReportProgress方法则会启动ProgressChanged事件的事件处理,而当DoWork事件处理完成时,则会触发RunWorkerCompleted事件。您必须非常小心,确保在 DoWork 事件处理程序中不操作任何用户界面对象(否则仍会停止响应)。而应该通过 ProgressChanged和 RunWorkerCompleted 事件与用户界面进行通信。

实现waitefrom界面的窗体,改界面自己设计。

技术分享
 1 /// <summary>
 2         /// 当辅助线程指示某些操作已经进行时引发
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
 7         {
 8             int progress = e.ProgressPercentage;
 9             this.progressBar1.Value = progress;
10             //label1.Content = string.Format("{0}", progress);
11         }
12 
13         /// <summary>
14         /// 操作开始时在另一个线程上运行的事件处理程序
15         /// </summary>
16         /// <param name="sender"></param>
17         /// <param name="e"></param>
18         private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
19         {
20             
21         }
22 
23         /// <summary>
24         /// 当辅助线程完成(无论是成功,失败或者取消)时引发
25         /// </summary>
26         /// <param name="sender"></param>
27         /// <param name="e"></param>
28         private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
29         {
30             this.DialogResult = DialogResult.OK;
31         }
View Code

调用waitefrom船体代码(DoWork事件不要重复使用)

技术分享
 1  protected virtual void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
 2         {
 3             BackgroundWorker bw = sender as BackgroundWorker;
 4             for (int i = 0; i < 100; i++)
 5             {
 6                 System.Threading.Thread.Sleep(1000);
 7                 WaiteForm1 f = e.Argument as WaiteForm1;
 8                 f.bw.ReportProgress(i);
 9                 bw.ReportProgress(i);
10             }
11             object a = e.Argument;
12             object b = e.Cancel;
13             e.Result = "21";
14         }
15 
16  private void button1_Click(object sender, EventArgs e)
17         {
18             WaiteForm1 wa = new WaiteForm1();
19 
20             //执行DoWork事件可传入执行的参数
21             wa.bw.RunWorkerAsync(wa);
22 
23             wa.bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
24             //wa.bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
25             wa.ShowDialog(this);
26             this.Text = "2132";
27         }
View Code

 

BackgroundWorker实现的winfrom中实现异步等待加载图片显示

标签:

原文地址:http://www.cnblogs.com/shangshen/p/4710690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!