先看一个小例子:C#客户端打开一个控件,控件中加载了好多数据大约要用5秒中,如果我们直接打开控件,那么这个控件就要5秒中才能弹出来,当然这个时候用户已经把他Kill了。这个时候我们就需要先给用户把控件UI加载出来,给出来一个假象,然后数据在后台加载就OK了。具体看一下怎么做。
public Form1()
{
InitializeComponent(); //如果要设置进度条和取消事件,则必须先设定他们的属性可以执行
backgroundWorker1.WorkerReportsProgress=true;
backgroundWorker1.WorkerSupportsCancellation=true; //注册要执行的耗时事件
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
//注册进度条事件
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
//注册执行完backgroundworker事件
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
} /// <summary>
/// 点击开始
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void startAsyncButton_Click(object sender, EventArgs e)
{
//这里做判断就是判断backgroundWorker是否在执行,如果没有在执行就开始工作,执行Dowork中的事件
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
} /// <summary>
/// 开始执行耗时事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = ; i <= ; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
else
{
Thread.Sleep();
//更改进度条值,触发进度条事件,这里不能实现UI代码,要在进度条改变事件里实现
worker.ReportProgress(i * );
}
}
} /// <summary>
/// 点击取消执行事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void cancelAsyncButton_Click(object sender, EventArgs e)
{
if (backgroundWorker1.WorkerSupportsCancellation == true)
{
// Cancel the asynchronous operation.
backgroundWorker1.CancelAsync();
}
} /// <summary>
/// 进度条改变事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
radLabel1.Text = (e.ProgressPercentage.ToString() + "%");
} /// <summary>
/// backgroundWorker1执行完事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
}
}
具体代码如下:
运行结果: