using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BackgroundThreading
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true;
}
private void
Form1_Load(object sender, EventArgs e)
{
}
private void
btnStart_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void btnCancel_Click(object sender, EventArgs
e)
{
backgroundWorker1.CancelAsync();
}
private void
backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//NOTE: we shouldn't use a try catch block here (unless you
rethrow the exception)
//the backgroundworker will be able to detect any exception
on this code.
//if any exception is produced, it will be available to you
on
//the RunWorkerCompletedEventArgs object, method
backgroundWorker1_RunWorkerCompleted
//try
//{
DateTime start = DateTime.Now;
e.Result = "";
for (int i = 1; i
<= 100; i++)
{
System.Threading.Thread.Sleep(50); //do some intense task here.
backgroundWorker1.ReportProgress(i, DateTime.Now);
//notify progress to main thread. We also pass
time information in UserState to cover this property in the example.
//Error
handling: uncomment this code if you want to test how an exception is handled
by the background worker.
//also uncomment the mentioned attribute above
to it doesn't stop in the debugger.
//if (i == 34)
//
throw new Exception("something wrong here!!");
//if cancellation is pending, cancel
work.
if
(backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
}
TimeSpan duration = DateTime.Now
- start;
//we could return some useful information here, like
calculation output, number of items affected, etc.. to the main thread.
e.Result = "Duration:
" + duration.TotalMilliseconds.ToString() + " ms.";
//}
//catch(Exception ex){
//
MessageBox.Show("Don't use try catch here, let the backgroundworker
handle it for you!");
//}
}
private void
backgroundWorker1_ProgressChanged(object
sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage; //update
progress bar
lblMessage.Text = e.ProgressPercentage + "%
completed...";
DateTime time = Convert.ToDateTime(e.UserState);
//get additional information about progress
//in this example, we log that optional additional info to
textbox
textBox1.AppendText(time.ToLongTimeString());
textBox1.AppendText(Environment.NewLine);
}
private void
backgroundWorker1_RunWorkerCompleted(object
sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("The task has been cancelled ");
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
}
else
{
MessageBox.Show("The task has been completed. Results: "
+ e.Result.ToString());
}
}
}
}