How to use C # BackgroundWorker

Source: Internet
Author: User

# Several instances of the BackgroundWorker control (C # BackgroundWorker use method):

In WinForms, sometimes a time-consuming operation is performed, and the user interface is manipulated before the operation is completed, causing the user interface to stop responding.
The solution is to open a new thread and put the time-consuming operations into the thread, so that you can do other things on the user interface.
New threads can be used with the thread class, can be multi-threaded simultaneous operation, simple can be achieved through the BackgroundWorker class.

Perform time-consuming operations with the BackgroundWorker class
The BackgroundWorker class is under the System.ComponentModel namespace.
VS's Toolbox has a BackgroundWorker component, which is the class.


Common methods

1.RunWorkerAsync
Begins a background operation. Raising the DoWork Event

2.CancelAsync
Request to cancel a pending background operation.
Note: This method is to set the Cancellationpending property to True and does not terminate the background operation. In the background operation, check the Cancellationpending property to determine whether you want to continue the time-consuming operation.

3.ReportProgress
Raises the ProgressChanged event.


Common Properties

1.CancellationPending
Indicates whether the application has requested cancellation of the background operation.
The read-only property, which defaults to False, evaluates to True when the CancelAsync method is executed.

2.WorkerSupportsCancellation
Indicates whether asynchronous cancellation is supported. To execute the CancelAsync method, you need to set the property to true first.

3.WorkerReportsProgress
Indicates whether progress can be reported. To execute the ReportProgress method, you need to set the property to true first.

Common events
1.DoWork
Occurs when the RunWorkerAsync method is called.

2.RunWorkerCompleted
Occurs when a background operation is completed, canceled, or an exception is thrown.

3.ProgressChanged
Occurs when the ReportProgress method is called.

No user interface objects are manipulated in the DoWork event handler. Instead, you should communicate with the user interface through the progresschanged and runworkercompleted events.


If you want to communicate with the control of the user interface in the DoWork event handler, you can use the ReportProgress method.
reportprogress (int percentprogress, Object userState), which can pass an object.


The ProgressChanged event can get this information object from the UserState property of the parameter ProgressChangedEventArgs class.

Simple implementation of step-up:

public BackgroundWorker bgworker = null;

constructor function:

Bgworker = new BackgroundWorker ();
Bgworker.dowork + = new Doworkeventhandler (bgworker_dowork);
bgworker.runworkercompleted + = new Runworkercompletedeventhandler (bgworker_runworkercompleted);
Bgworker.workersupportscancellation = true;//Whether asynchronous cancellation is supported

Start Start:

Bgworker.runworkerasync ();

Write the corresponding function data and execute the result.



Simple program with BackgroundWorker more convenient than thread, thread and control communication on the user interface is more troublesome, need to use a delegate to invoke the control's invoke or BeginInvoke method, no BackgroundWorker convenient.

============================

A simple gadget code that brushes Web traffic

1. Drag a BackgroundWorker control from the toolbar and set its properties workerreportsprogress to True

2. To have the worker start working, execute the following code:
Mbackgroundworker.runworkerasync (ARG);
Here is a rewrite if you do not need to pass parameters directly mbackgroundworker.runworkerasync ();

3. Edit the DoWork event code:
E.argument is Mbackgroundworker.runworkerasync (ARG); the corresponding parameter
The reason for using the progress bar is that there must be a loop that reports the progress in the loop:
Worker. ReportProgress (i * 100/totalnum, obj);
Where the first parameter is the percentage of the current progress, obj is the userstate you want to pass, and if there are no

4. Edit the ProgressChanged event code:
E.progresspercentage as a percentage of progress, E.userstate is the object just passed over
In this event, you can invoke the UI's progress bar and other controls:
Mtoolstripprogressbar.value = E.progresspercentage;

5. Edit the RunWorkerCompleted event code:
The work is done tell the UI

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Text;
Using System.Windows.Forms;
Using System.Net;
Using System.Threading;

Namespace WindowsApplication15
{
public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
}

private void Button1_Click (object sender, EventArgs e)
{
TextBox1.Text Inside Store URL
Backgroundworker1.runworkerasync (TextBox1.Text);
}

private void Backgroundworker1_dowork (object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = (BackgroundWorker) sender;
String url = e.argument.tostring ();

for (int i = 0; i <; i++)
{
No background operation canceled
if (!BW. cancellationpending)
{
WebRequest req = webrequest.create (URL);
WebResponse resp = req. GetResponse ();
Resp. Close ();

Thread.Sleep (1000);
Bw. ReportProgress (i * 100/10, i);
}
}
}

private void Backgroundworker1_progresschanged (object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = E.progresspercentage;
Label1. Text = E.userstate.tostring ();
}

private void Backgroundworker1_runworkercompleted (object sender, Runworkercompletedeventargs e)
{
MessageBox.Show ("ok! ");
}
}
}

======================

http://hi.baidu.com/yebihaigsino/blog/item/eeccbb02fdf1228fd43f7c8a.html more advanced BackgroundWorker Control instance applications

===================

http://blog.163.com/j_yd168/blog/static/4967972820092114269195/c# BackgroundWorker A small example of multithreaded operations

============ ================ This example contains database operations

First, BackgroundWorker work steps

1. Drag a BackgroundWorker control into the form.

2. In a method or event, call BackgroundWorker's RunWorkerAsync () method.

3. This method is an asynchronous operation that will automatically raise the BackgroundWorker DoWork event.

4. Calling the ReportProgress method raises the ProgressChanged event.

Second used the example of BackgroundWorker.

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Text;
Using System.Windows.Forms;
Using System.Threading;
Using System.Data.SqlClient;


The use case requires a SQL Server database named Bgwtestdb
The database should contain a tbbgwtest table.
There are data1, data2 two columns in the table.
A stored procedure is also required in the database, and the SQL statement is as follows:

Namespace Winbackgroundworkertest
{
public partial class Backgroundworkertest:form
{
int count = 30;

Public Backgroundworkertest ()
{
InitializeComponent ();
}

private void btnAdd_Click (object sender, EventArgs e)
{
1. Call Bgwinsertdata's RunWorkerAsync method, which is used to raise the DoWork event
Bgwinsertdata.runworkerasync (count);
}

private void Bgwinsertdata_dowork (object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
2. Call the custom function in DoWork and pass the sender that raised the DoWork event
InsertData (worker);
}

private void Bgwinsertdata_progresschanged (object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = E.progresspercentage;
}

Custom Function InsertData ()
private void InsertData (BackgroundWorker worker)
{
SqlConnection conn = new SqlConnection (@ "Data source=./sqlexpress;initial catalog=bgwtestdb;integrated security=true" );

SqlCommand cmd = new SqlCommand ("Insertonedata", conn);
Cmd.commandtype = CommandType.StoredProcedure;
Cmd. Parameters.Add ("Data1", SqlDbType.NChar, 10);
Cmd. Parameters.Add ("Data2", SqlDbType.Int);

for (int i = 0; i < count; i++)
{
Try
{
Conn. Open ();
Cmd. parameters["Data1"]. Value = i + 1;
Cmd. parameters["Data2"]. Value = i + 1;
Cmd. ExecuteNonQuery ();

3. Call the worker's reportprogress function to raise the event progresschanged
Worker. ReportProgress (i, worker);
}
catch (Exception ex)
{
MessageBox.Show (ex. Message);
}
Finally
{
IF (Conn. state = = ConnectionState.Open)
Conn. Close ();
}

Thread.Sleep (50);
}
}

private void Bgwinsertdata_runworkercompleted (object sender, Runworkercompletedeventargs e)
{
if (e.error! = null)
{
MessageBox.Show (e.error.message, "hint", MessageBoxButtons.OK, Messageboxicon.error);
Return
}
else if (e.cancelled)
{
MessageBox.Show ("Cancel operation! "," hint ", MessageBoxButtons.OK, MessageBoxIcon.Information);
Return
}
Else
MessageBox.Show ("Operation succeeded! "," hint ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}

C # BackgroundWorker How to use

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.