public
void
RunWorkerAsync
();
public
void
RunWorkerAsync
(
Object
argument);
|
public
void
CancelAsync();
|
public
void
ReportProgress
(
int
percentProgress);
public
void
ReportProgress
(
int
percentProgress,
Object
userState);
|
public
bool
CancellationPending
{ get; }
public
bool
WorkerReportsProgress
{ get; set; }
public
bool
WorkerSupportsCancellation
{ get; set; }
|
public
bool
IsBusy { get; }
|
public
event
DoWorkEventHandler
DoWork;
public
event
ProgressChangedEventHandler
ProgressChanged;
public
event
RunWorkerCompletedEventHandler
RunWorkerCompleted;
|
private
System.ComponentModel.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);
}
|
private
void startAsyncButton_Click(object sender, EventArgs e)
{
resultLabel.Text = String.Empty;
this.numericUpDown1.Enabled = false;
this.startAsyncButton.Enabled = false;
this.cancelAsyncButton.Enabled = true;
//
获取计算数值.
int numberToCompute = (int)numericUpDown1.Value;
//
启动异步操作.
backgroundWorker1.RunWorkerAsync(numberToCompute);
}
|
void
backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = ComputeAdd((int)e.Argument, worker, e);
}
|
private
long ComputeAdd(int n, BackgroundWorker worker, DoWorkEventArgs e)
{
long result = 0;
for (int i = 1; i <= n; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
break;
}
else
{
result += i;
Thread.Sleep(500);
int percentComplete = (int)((float)i / (float)n * 100);
worker.ReportProgress(percentComplete);
}
}
return result;
}
|
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 = e.Result.ToString();
}
this
.numericUpDown1.Enabled = true;
startAsyncButton.Enabled = true;
cancelAsyncButton.Enabled = false;
}
|
public
ProcessForm(BackgroundWorker backgroundWorker1)
{
InitializeComponent();
this.backgroundWorker1 = backgroundWorker1;
this.backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
this.backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
void
backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
void
backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
private
void cancelButton1_Click(object sender, EventArgs e)
{
this.backgroundWorker1.CancelAsync();
this.cancelButton1.Enabled = false;
this.Close();
}
|
private
void startAsyncButton_Click(object sender, EventArgs e)
{
// ...
backgroundWorker1.RunWorkerAsync(numberToCompute);
ProcessForm form = new ProcessForm(this.backgroundWorker1);
form.ShowDialog(this);//
模式
//form.Show(this);//
非模式
}
|
public
void
Post
(
SendOrPostCallback
d,
Object
arg);
public
void
PostOperationCompleted
(
SendOrPostCallback
d,
Object
arg);
|
public
delegate
void
SendOrPostCallback
(
Object
state);
|
private
delegate void WorkerThreadStartDelegate(object argument);
private
readonly WorkerThreadStartDelegate threadStart;
public
BackgroundWorker()
{
this
.threadStart = new WorkerThreadStartDelegate(this.WorkerThreadStart);
//…
}
|
public
void RunWorkerAsync(object argument)
{
if (this.isRunning)
{
throw new InvalidOperationException(SR.GetString("BackgroundWorker_WorkerAlreadyRunning"));
}
this.isRunning = true;
this.cancellationPending = false;
this.asyncOperation = AsyncOperationManager.CreateOperation(null);
this.threadStart.BeginInvoke(argument, null, null);
}
|
private
void WorkerThreadStart(object argument)
{
object result = null;
Exception error = null;
bool cancelled = false;
try
{
DoWorkEventArgs e = new DoWorkEventArgs(argument);
this.OnDoWork(e);
if (e.Cancel)
{
cancelled = true;
}
else
{
result = e.Result;
}
}
catch (Exception exception2)
{
error = exception2;
}
RunWorkerCompletedEventArgs arg = new RunWorkerCompletedEventArgs(result, error, cancelled);
this.asyncOperation.PostOperationCompleted(this.operationCompleted, arg);
}
|
public
void ReportProgress(int percentProgress, object userState)
{
if (!this.WorkerReportsProgress)
{
throw new InvalidOperationException(SR.GetString("BackgroundWorker_WorkerDoesntReportProgress"));
}
ProgressChangedEventArgs arg = new ProgressChangedEventArgs(percentProgress, userState);
if (this.asyncOperation != null)
{
this.asyncOperation.Post(this.progressReporter, arg);
}
else
{
this.progressReporter(arg);
}
}
|
public
BackgroundWorker()
{
this
.threadStart = new WorkerThreadStartDelegate(this.WorkerThreadStart);
this
.operationCompleted = new SendOrPostCallback(this.AsyncOperationCompleted);
this.progressReporter = new SendOrPostCallback(this.ProgressReporter);
}
private
void ProgressReporter(object arg)
{
this.OnProgressChanged((ProgressChangedEventArgs)arg);
}
private
void AsyncOperationCompleted(object arg)
{
this.isRunning = false;
this.cancellationPending = false;
this.OnRunWorkerCompleted((RunWorkerCompletedEventArgs)arg);
}
|
public
void RunWorkerAsync(object argument)
{
if (this.isRunning)
{
throw new InvalidOperationException(SR.GetString("BackgroundWorker_WorkerAlreadyRunning"));
}
this.isRunning = true;
this.cancellationPending = false;
this.asyncOperation = AsyncOperationManager.CreateOperation(null);
this.threadStart.BeginInvoke(argument, null, null);
}
public
void CancelAsync()
{
if (!this.WorkerSupportsCancellation)
{
throw new InvalidOperationException(SR.GetString("BackgroundWorker_WorkerDoesntSupportCancellation"));
}
this.cancellationPending = true;
}
|
注:本文轉自http://blog.csdn.net/zhzuo/archive/2008/07/23/2699305.aspx