Created
April 30, 2012 10:49
-
-
Save AndrewBarfield/2557331 to your computer and use it in GitHub Desktop.
C#: Windows Forms: Using a BackgroundWorker with a progress bar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
using System.Threading; | |
namespace BackgroundWorker | |
{ | |
public partial class Form1 : Form | |
{ | |
public Form1() | |
{ | |
InitializeComponent(); | |
} | |
private void backgroundWorker1_DoWork( object sender, DoWorkEventArgs e ) | |
{ | |
for ( int i = 0 ; i < 101 ; i++ ) | |
{ | |
if ( backgroundWorker1.CancellationPending ) | |
{ | |
e.Cancel = true; | |
break; | |
} | |
backgroundWorker1.ReportProgress( i ); | |
Thread.Sleep( 20 ); | |
} | |
e.Result = 0; | |
} | |
private void backgroundWorker1_ProgressChanged( object sender, ProgressChangedEventArgs e ) | |
{ | |
progressBar1.Value = e.ProgressPercentage; | |
label1.Text = e.ProgressPercentage + "% complete"; | |
} | |
private void backgroundWorker1_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e ) | |
{ | |
if ( e.Cancelled ) | |
{ | |
label1.Text = "Operation cancelled"; | |
} | |
else | |
{ | |
label1.Text = "Operation Complete"; | |
} | |
buttonCancel.Enabled = false; | |
buttonStart.Enabled = true; | |
} | |
private void buttonStart_Click( object sender, EventArgs e ) | |
{ | |
buttonCancel.Enabled = true; | |
buttonStart.Enabled = false; | |
backgroundWorker1.RunWorkerAsync(); | |
} | |
private void buttonCancel_Click( object sender, EventArgs e ) | |
{ | |
buttonCancel.Enabled = false; | |
backgroundWorker1.CancelAsync(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment