Programming asynchronous operations using the BackgroundWorker component

Source: Internet
Author: User

Overview

In an application, you may experience time-consuming functional operations, such as data downloads, complex computations, and database transactions, which are typically implemented on a separate thread, and the results are displayed to the user interface at the end of execution, which avoids the user interface being unresponsive for a long time. In. NET 2.0 and later versions, FCL provides BackgroundWorker components to facilitate the implementation of these functional requirements.

Component Introduction

The BackgroundWorker class is located in the System.ComponentModel namespace, which implements an event-based asynchronous pattern by performing operations on a separate thread. The following is an introduction to the main members of the BackgroundWorker class.

The 1th Main method of the BackgroundWorker class is RunWorkerAsync, which submits a request to start the operation asynchronously, and when the request is made, the DoWork event is raised and the asynchronous operation code is started in the event handler. The RunWorkerAsync method is signed as follows,

public void RunWorkerAsync ();

public void RunWorkerAsync (Object argument);

If an asynchronous operation requires an action argument, it can be supplied as a argument parameter, and because the parameter type is object, a type conversion may be required for access.

The CancelAsync method commits a request to terminate an asynchronous operation and sets the Cancellationpending property to True. Note whether the CancelAsync method succeeds in calling the Workersupportscancellation property, and if the asynchronous operation is allowed to be canceled, set the Workersupportscancellation property to True , otherwise calling the method throws an exception. The CancelAsync method does not contain parameters, and the method signature is as follows

public void CancelAsync ();

When the CancelAsync method is invoked, the value of the BackgroundWorker's Cancellationpending property is set to true, so when writing a secondary method that executes in a separate thread, The Cancellationpending property should be checked periodically in your code to see if the property is set to True and, if true, to end the execution of the auxiliary method. It is important to note that the code in the DoWork event handler might have finished processing when the cancellation request was made, so the DoWork event handler or helper method might miss the time to set the Cancellationpending property to True. In this case, the cancelled flag of the Runworkercompletedeventargs parameter in the RunWorkerCompleted event handler is not set to CancelAsync even if the call to the calling method emits a cancel asynchronous operation request True, this is a competitive condition that often occurs in multithreaded programming, so you need to think about writing code.

When performing an asynchronous operation, if you need to track the progress of an asynchronous operation, the BackgroundWorker class provides a reportprogress method that invokes this method to raise the ProgressChanged event. Gets the asynchronous execution progress information in an event handler by registering the event. The method signature is as follows:

public void reportprogress (int percentprogress);

public void reportprogress (int percentprogress,object userState);

The method contains two versions, percentprogress represents a progress percentage, and the value is 0-100,userstate to represent the custom user state as an optional parameter.

As with the CancelAsync method, the ReportProgress method will invoke success when the Workerreportsprogress property of BackgroundWorker is set to true. Otherwise, a InvalidOperationException exception is thrown.

The 3 properties of BackgroundWorker are mentioned above, and cancellationpending is used to indicate whether the operation has been canceled. Workerreportsprogress and workersupportscancellation are used to set whether to allow progress reporting and cancel operations, respectively.

public bool cancellationpending {get;}

public bool Workerreportsprogress {get; set;}

public bool Workersupportscancellation {get; set;}

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.