BackgroundWorker controls in C #

Source: Internet
Author: User

Keywords: C # . NET BackgroundWorker
source:http://txw1958.cnblogs.com/


BackgroundWorker is a control used in the. NET Framework to perform multithreaded tasks, which allows developers to perform some operations on a separate thread. Time-consuming operations, such as downloads and database transactions, can cause the user interface (UI) to always be in a stopped-responding state during long runs. If you need a responsive user interface and are faced with long delays associated with such operations, you can use the BackgroundWorker class to easily resolve the issue.

To perform time-consuming operations in the background, create a backgroundworker that listens for events that report the progress of the operation and signal when the operation is complete. You can create BackgroundWorker programmatically, or you can drag it from the Components tab of the Toolbox onto the form. If you create a BackgroundWorker in the Windows Forms Designer, it appears in the component tray, and its properties are displayed in the Properties window.

Grammar
public class Backgroundworker:component

constructor function
name description
BackgroundWorker Initializes a new instance of the BackgroundWorker class.
Property
name description
Cancellationpending Gets a value indicating whether the application has requested to cancel the background operation.
Canraiseevents Gets a value that indicates whether the component can raise events. (inherited from Component.) )
Container Gets the IContainer that contains the Component. (inherited from Component.) )
DesignMode Gets a value that indicates whether the Component is currently in design mode. (inherited from Component.) )
Events Gets the list of event handlers attached to this Component. (inherited from Component.) )
IsBusy Gets a value that indicates whether BackgroundWorker is running an asynchronous operation.
Site Gets or sets the ISite of the Component. (inherited from Component.) )
Workerreportsprogress Gets or sets a value that indicates whether BackgroundWorker can report progress updates.
Workersupportscancellation Gets or sets a value that indicates whether BackgroundWorker supports asynchronous cancellation.
Method
name description
CancelAsync Request to cancel a pending background operation.
Createobjref Creates an object that contains all the relevant information required to generate a proxy for communicating with a remote object. (inherited from MarshalByRefObject.) )
Dispose () Releases all resources used by the Component. (inherited from Component.) )
Dispose (Boolean) Frees the unmanaged resources that the Component occupies, optionally releasing the managed resources. (inherited from Component.) )
Equals (Object) Determines whether the specified object is equal to the current object. (Inherit from Object.) )
Finalize Frees unmanaged resources and performs other cleanup operations before Component are reclaimed by garbage collection. (inherited from Component.) )
GetHashCode Serves as a hash function for a particular type. (Inherit from Object.) )
Getlifetimeservice Retrieves the current lifetime service object that controls the lifetime policy of this instance. (inherited from MarshalByRefObject.) )
GetService Returns an object that represents the service provided by Component or its Container. (inherited from Component.) )
GetType Gets the Type of the current instance. (Inherit from Object.) )
InitializeLifetimeService Gets the lifetime service object that controls the lifetime policy for this instance. (inherited from MarshalByRefObject.) )
MemberwiseClone () Creates a shallow copy of the current Object. (Inherit from Object.) )
MemberwiseClone (Boolean) Creates a shallow copy of the current MarshalByRefObject object. (inherited from MarshalByRefObject.) )
Ondowork Raises the DoWork event.
Onprogresschanged Raises the ProgressChanged event.
onrunworkercompleted Raises the RunWorkerCompleted event.
ReportProgress (Int32) Raises the ProgressChanged event.
ReportProgress (Int32, Object) Raises the ProgressChanged event.
RunWorkerAsync () Begins a background operation.
RunWorkerAsync (Object) Begins a background operation.
Tostring Returns a String (if any) that contains the name of the Component. This method should not be overridden. (inherited from Component.) )
Event
name description
Disposed Occurs when a component is freed by calling the Dispose method. (inherited from Component.) )
DoWork Occurs when RunWorkerAsync is called.
ProgressChanged Occurs when ReportProgress is called.
RunWorkerCompleted Occurs when a background operation is completed, canceled, or an exception is thrown.

Example

This code runs the environment: Windows XP, Visual Studio,. NET Framework 4, C #

The following code example demonstrates the time-consuming basics of asynchronous execution of the BackgroundWorker class. Shows an example of the output.

To try this code, you can create a Windows forms application. Add a Label control named ResultLabel and add two Button controls named Startasyncbutton and Cancelasyncbutton. Create the Click event handler for both buttons. From the Components tab in the Toolbox, add the BackgroundWorker component named BackgroundWorker1. Create runworkercompleted event handlers for DoWork, ProgressChanged, and BackgroundWorker.

In the form's code, replace the existing code with the following code.

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;namespace windowsformsapplication5{public partial            Class Form1:form {public Form1 () {InitializeComponent ();            Backgroundworker1.workerreportsprogress = true;        Backgroundworker1.workersupportscancellation = true; private void Startasyncbutton_click (object sender, EventArgs e) {if (backgroundworker1.isbusy            ! = True) {//Start asynchronous Operation Backgroundworker1.runworkerasync ();        } this.startAsyncButton.Enabled = false; private void Cancelasyncbutton_click (object sender, EventArgs e) {if (backgroundworker1.worker            Supportscancellation = = true) {//Cancel asynchronous Operation Backgroundworker1.cancelasync ();           } This.startAsyncButton.Enabled = true; }//The implementation of the main task private void Backgroundworker1_dowork (object sender, DoWorkEventArgs e) {backg            Roundworker worker = sender as BackgroundWorker; for (int i = 1; i <=; i++) {if (worker.                    Cancellationpending = = true) {E.cancel = true;                Break } else {//Perform a timing operation and report progress System.Threading.Thread.Sleep                    (500); Worker.                ReportProgress (i * 10); }}}//Update progress private void Backgroundworker1_progresschanged (object sender, ProgressChanged        EventArgs e) {resultlabel.text = (e.progresspercentage.tostring () + "%");         }//Process background operation result private void backgroundworker1_runworkercompleted (object sender, Runworkercompletedeventargs e) {if (e.cancelled = = True) {Resultlabel.text = "canceled!";            } else if (e.error! = null) {Resultlabel.text = "Error:" + e.error.message;            } else {resultlabel.text = "done!"; }        }    }}

BackgroundWorker controls in C #

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.