Windows Forms: BackgroundWorker in C#
By FoxLearn 6/1/2017 8:14:19 PM 6.96K
How to use a Background Worker in C#. The Background Worker class allows you to run an operation on a separate, dedicated thread.
When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.
Step 1: Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "BackgroundWorkerExample" and then click OK
Step 2: Design your form as below
Step 3: Add a click event handler to the button
struct DataParameter { public int Process; public int Delay; } private DataParameter _inputparameter; //Update progress bar private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { progress.Value = e.ProgressPercentage; lblPercent.Text = string.Format("Processing...{0}%", e.ProgressPercentage); progress.Update(); } private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) { //Set parameter int process = ((DataParameter)e.Argument).Process; int delay = ((DataParameter)e.Argument).Delay; int index = 1; try { for (int i = 0; i < process; i++) { if (!backgroundWorker.CancellationPending) { backgroundWorker.ReportProgress(index++ * 100 / process, string.Format("Process data {0}", i)); Thread.Sleep(delay);//used to simulate length of operation //Add your code here... } } } catch (Exception ex) { backgroundWorker.CancelAsync(); MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { MessageBox.Show("Process has been completed.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } //Run backgroundworker private void btnStart_Click(object sender, EventArgs e) { if (!backgroundWorker.IsBusy) { _inputparameter.Delay = 10; _inputparameter.Process = 1200; backgroundWorker.RunWorkerAsync(_inputparameter); } } private void btnStop_Click(object sender, EventArgs e) { if (backgroundWorker.IsBusy) backgroundWorker.CancelAsync(); }
VIDEO TUTORIALS
- How to make a Notepad in C#
- How to Receive SMS from WhatsApp in C#
- How to Add Combobox to DataGridView in C#
- How to Create Multiple pages on the Form using Panel control in C#
- How to insert Math Equation to RichTextBox in C#
- How to Send and Receive email in Microsoft Outlook using C#
- How to Print Windows Form in C#
- How to Use Form Load and Button click Event in C#
Categories
Popular Posts
How to sign a powershell script
10/03/2024