Time-consuming operations performed in the background in WinForms

Source: Internet
Author: User

In WinForms, sometimes time-consuming operations are required. operations on the user interface before the operation is completed may cause the user interface to stop responding.

The solution is to open a new thread and place the time-consuming operations in the thread for execution, so that other operations can be performed on the user interface.

The Thread class can be used to create a new Thread, and multiple threads can be operated simultaneously. It can be simply implemented through the BackgroundWorker class.

Use the BackgroundWorker class to perform time-consuming operations

The BackgroundWorker class is in the namespace of System. ComponentModel.

The VS toolbox has a BackgroundWorker component, which is the class.



Common Methods

1. RunWorkerAsync

Start background operations. Trigger a DoWork event


2. CancelAsync

Cancels the pending background operation.
Note: This method sets the CancellationPending attribute to true and does not terminate background operations. In background operations, you must check the CancellationPending attribute to determine whether to continue time-consuming operations.

3. ReportProgress

Raise the ProgressChanged event.



Common attributes

1. CancellationPending

Indicates whether the application has requested to cancel background operations.

Read-only attribute. The default value is false. If the CancelAsync method is executed, the value is true.

2. workersuppscanscancellation

Indicates whether asynchronous cancellation is supported. To execute the CancelAsync method, you must first set this attribute to true.


3. WorkerReportsProgress

Indicates whether progress can be reported. To execute the ReportProgress method, you must first set this attribute to true.


Common events
1. DoWork

The RunWorkerAsync method is called.


2. RunWorkerCompleted

The background operation has been completed, canceled, or thrown an exception.

3. ProgressChanged

The ReportProgress method is called.




Example

Private BackgroundWorker backgroundWorker = new BackgroundWorker ();


Private void button#click (object sender, EventArgs e)

{

BackgroundWorker. WorkerReportsProgress = true;

BackgroundWorker. workersuppscanscancellation = true;


// Bind the background operation to be executed

BackgroundWorker. DoWork + = new DoWorkEventHandler (backgroundWorker_DoWork );



// Method to be executed after binding the background operation is complete

BackgroundWorker. RunWorkerCompleted + = new RunWorkerCompletedEventHandler (backgroundWorker_RunWorkerCompleted );



// Method for controlling the progress

BackgroundWorker. ProgressChanged + = new ProgressChangedEventHandler (backgroundWorker_ProgressChanged );


// Trigger the DoWork event. In this case, the backgroundWorker_DoWork method is executed in the thread.

BackgroundWorker. RunWorkerAsync ();


Button1.Enabled = false;

}


Private void button2_Click (object sender, EventArgs e)

{

BackgroundWorker. CancelAsync (); // request to cancel the pending background operation

}


// The controls on the user interface cannot be accessed here

Private void backgroundWorker_DoWork (object sender, DoWorkEventArgs e)

{

System. Threading. Thread. Sleep (5000 );


// Report the progress and raise the ProgressChanged event

BackgroundWorker. ReportProgress (50); // 50% is completed here


If (! BackgroundWorker. CancellationPending) // determines whether the CancelAsync method is executed.

{

System. Threading. Thread. Sleep (5000 );

}

Else

{

MessageBox. Show ("aborted. ");

}

}


Private void backgroundWorker_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e)

{

// You can access the controls on the user interface.

Button1.Enabled = true;

}


Private void backgroundWorker_ProgressChanged (object sender, ProgressChangedEventArgs e)

{

// Generally, the progress is displayed through the ProgressBar class.

MessageBox. Show (e. ProgressPercentage. ToString ());


// E. ProgressPercentage, e. UserState

}




In the DoWork event handler, no user interface objects are operated. You should use the ProgressChanged and RunWorkerCompleted events to communicate with the user interface.

If you want to communicate with the control on the user interface in the DoWork event handler, you can use the ReportProgress method.

ReportProgress (int percentProgress, object userState), you can pass an object.

The ProgressChanged Event can be obtained from the UserState attribute of the ProgressChangedEventArgs class.

Simple programs use BackgroundWorker, which is easier to communicate with the control on the user interface than Thread. Therefore, you need to use a delegate to call the control's Invoke or BeginInvoke method, which is convenient without BackgroundWorker.

Http://www.huanghengxu.com/Html/Article/57.htm

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.