c#異步操作后臺(tái)運(yùn)行(backgroundworker類)示例
c#異步操作,BackgroundWorker類的使用,可以在后臺(tái)運(yùn)行需要的代碼邏輯。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace TestBackgroundWork
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitializeBackgoundWorker();
}
private BackgroundWorker backgroundWorker1;
private void InitializeBackgoundWorker()
{
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
//**********backgroundWorker1的回調(diào)函數(shù)**********
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
}
else
{
Thread.Sleep(500);
int percentComplete = (int)((float)i / (float)10 * 100);
worker.ReportProgress(percentComplete);
}
}
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
resultLabel.Text = "Canceled";
}
else
{
resultLabel.Text = "Completed";
}
startBtn.Enabled = true;
stopBtn.Enabled = false;
}
//**********backgroundWorker1的回調(diào)函數(shù)**********
private void startBtn_Click(object sender, EventArgs e)
{
resultLabel.Text = String.Empty;
this.startBtn.Enabled = false;
this.stopBtn.Enabled = true;
//啟動(dòng)異步操作.
backgroundWorker1.RunWorkerAsync();
}
private void stopBtn_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
}
}
}
相關(guān)文章
C#實(shí)現(xiàn)六大設(shè)計(jì)原則之里氏替換原則
這篇文章介紹了C#實(shí)現(xiàn)六大設(shè)計(jì)原則之里氏替換原則的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-02-02C#實(shí)現(xiàn)計(jì)算年齡的簡(jiǎn)單方法匯總
本文給大家分享的是C#代碼實(shí)現(xiàn)的簡(jiǎn)單實(shí)用的給出用戶的出生日期,計(jì)算出用戶的年齡的代碼,另外附上其他網(wǎng)友的方法,算是對(duì)計(jì)算年齡的一次小結(jié),希望大家能夠喜歡。2015-05-05C#中ExecuteNonQuery()返回值注意點(diǎn)分析
這篇文章主要介紹了C#中ExecuteNonQuery()返回值注意點(diǎn)分析,對(duì)于C#數(shù)據(jù)庫(kù)程序設(shè)計(jì)有很大的借鑒價(jià)值,需要的朋友可以參考下2014-08-08