大学IT网 - 最懂大学生的IT学习网站! QQ资料交流群:367606806
当前位置:大学IT网 > C#技巧 > 异步调用backgroudworker

异步调用backgroudworker

关键词:异步调用backgroudworker  阅读(686) 赞(18)

[摘要]本文是对异步调用backgroudworker的讲解,对学习C#编程技术有所帮助,与大家分享。

先看一个小例子:C#客户端打开一个控件,控件中加载了好多数据大约要用5秒中,如果我们直接打开控件,那么这个控件就要5秒中才能弹出来,当然这个时候用户已经把他Kill了。这个时候我们就需要先给用户把控件UI加载出来,给出来一个假象,然后数据在后台加载就OK了。具体看一下怎么做。

首先在面板中加载一个BackgroundWorder组件,然后在加载窗体中时注册几个事件:

1.BackgroundWorder启动事件。就是加载后台5秒中代码;BackgroundWorder.DoWork事件;

backgroundWorker1.DoWork += backgroundWorker1_DoWork;

2.BackgroundWorder加载中事件。这个事件可以写当前的加载进度,或者错误事件;BackgroundWorder.ProgressChanged事件;

backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;

3.BackgroundWorder结束事件。就是数据加载完毕做什么事情或者异步出错给出提示什么的,

BackgroundWorder.RunWorkerCompleted事件。

backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;

具体代码如下:

    public Form1()
{
InitializeComponent();

backgroundWorker1.DoWork += backgroundWorker1_DoWork;

backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}

     private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { } private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) { radLabel1.Text = (e.ProgressPercentage.ToString() + "%"); } private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
BackgroundWorker worker = sender as BackgroundWorker; for (int i = 1; i <= 10; i++) { if (worker.CancellationPending) { e.Cancel = true; break; } else { Thread.Sleep(500); worker.ReportProgress(i * 10); } } }

运行结果:



相关评论