WPF中使用BackgroundWorder

来源:转载

声明成员变量

/// <summary>/// BackgroundWorker对象/// </summary>BackgroundWorker myBackgroundWorker;

初始化BackgroundWorder

/// <summary>/// 初始化BackgroundWorker对象/// </summary>private void InitBackgroundWorker(){ myBackgroundWorker = new BackgroundWorker(){ WorkerReportsProgress = true, WorkerSupportsCancellation = true }; myBackgroundWorker.DoWorker += myBackgroundWorker_DoWork; myBackgroundWorker.ProgressChanged += myBackgroundWorker_ProgressChanged; myBackgroundWorker.RunWorkerCompleted += myBackgroundWorker_RunWorkerCompleted;}

开始工作事件

/// <summary>/// 开始工作/// </summary>/// <param></param>/// <param></param>private void myBackgroundWorker_DoWork(object sender,DoWorkEventArgs e){ //接收参数 object obj = e.Argument; //停止功能(可以在循环中多放置一些,让程序更快的响应停止功能) if(e.Cancel || ((BackgroundWorker)sender).CancellationPending) { return; } //做一些事情 //do something... //更新进度 ((BackgroundWorker)sender).ReportProgress((当前数/总数[需要时Int]),string.Format("可以给提示文字:{0}",(当前数/总数));}

进度更新

/// <summary>/// 更新进度事件/// </summary>/// <param></param>/// <param></param>private void myBackgroundWorker_ProgressChanged(object sender,ProgressChangedEventArgs e){ //进度提示文字 XXX.Text = e.UserState.ToString(); //进度条 XXX.Value = e.ProgressPercentage;}

运行完成

/// <summary>/// 工作完成事件/// </summary>/// <param></param>/// <param></param>private void myBackgroundWorker_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e){ //更新界面提示 XXX.Text = "已完成XXX"; //进度条 XXX.Value = 这里给进度条最大值; //释放资源 ((BackgroundWorker)sender).Disposs();}

创建一个新的Worker,这个方法在要中断之前的Worker并且继续进行查询时使用

/// <summary>/// 开启新的Worker/// </summary>/// <param>运行参数</param>private void openNewWorker(object sourceArgument){ //判断是否为空 if(myBackgroundWorker != null) { //判断是否处于忙碌中 if(myBackgroundWorker.IsBusy) { //发出停止指令 myBackgroundWorker.CancelAsync(); } } //实例化一个新的Worker myBackgroundWorker = new BackgroundWorker(){ WorkerReportsProgress = true, WorkerSupportsCancellation = true }; myBackgroundWorker.DoWorker += myBackgroundWorker_DoWork; myBackgroundWorker.ProgressChanged += myBackgroundWorker_ProgressChanged; myBackgroundWorker.RunWorkerCompleted += myBackgroundWorker_RunWorkerCompleted; //运行这个Worker myBackgroundWorker.RunWorkerAsync(sourceArgument);}

这是本人在使用中积攒下来的一点经验,欢迎大家提出意见,我们一起讨论。

分享给朋友:
您可能感兴趣的文章:
随机阅读: