Backgroundworker threads
In a triggered method, create the events if the thread has to be created. Implement 3 events. The work event, the completed event and de progress changed event. This does not trigger the thread, but only implements the functionality
private void InitializeBackgoundWorker()
{
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler( backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler( backgroundWorker1_ProgressChanged);
}
Example implementation DoWork event:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
e.Result = DoLongWork((int)e.Argument, worker, e);
}
The sender is de background worker. The eventargs contain the option for cancelling the operation. The worker object tells abut the status. The user could have choosen to cancel the operation. If the consuming time function is executing. The worker status can be questionned along the way. A user could have choosen the cancel the operation.
if (worker.CancellationPending) { e.Cancel = true; }
With the function backgroundWorker1.CancelAsync(); the thread can be cancelled.With the function backgroundWorker1.RunWorkerAsync(numberToCompute); the thread can be started.
After completing or cancelling the thread the Completed event will be triggered
private void backgroundWorker1_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { }
The eventargs contains the result.
e has attribute error. The e.Error can be set in the DoWork event
e has attribute cancelled. The e.Cancelled can be set in the DoWork event
e has attribute result. Also can be set in the DoWork event.
In the DoWork event the progress can be reported. Call worker.ReportProgress(percentComplete);
In the event handler of ProgessChanged read the value:
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
textBoxCompleted.Text = e.ProgressPercentage.ToString() + "% completed";
}
No comments:
Post a Comment