VB version here.
Create a new Windows Forms project. Add a Label, a ProgressBar and a BackgroundWorker to the form. Set the BackgroundWorker's WorkerReportsProgress property to True. Add the following code then run the project.
CSharp Code:
private void Form1_Load(object sender, EventArgs e)
{
// Raise the DoWork event in a worker thread.
this.backgroundWorker1.RunWorkerAsync();
}
// This method is executed in a worker thread.
private void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
BackgroundWorker worker = (BackgroundWorker)sender;
for (int i = 1; i <= 100; i++)
{
// Raise the ProgressChanged event in the UI thread.
worker.ReportProgress(i, i + " iterations complete");
// Perform some time-consuming operation here.
System.Threading.Thread.Sleep(250);
}
}
// This method is executed in the UI thread.
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
this.label1.Text = e.UserState as string;
}
// This method is executed in the UI thread.
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
this.label1.Text = "Operation complete";
}
Note that if you paste that code into your own form you'll need to go to the Properties window in the designer to attach the event handlers for it to work.