Backgroundworker: running operations in the background

Source: Internet
Author: User

If there is an operation that takes a long time to complete, and you do not want latency in the user interface, you can use the backgroundworker class to run this operation on another thread.

The following code example demonstrates how to run time-consuming operations in the background. This form has the start and cancel buttons. Click Start to run the asynchronous operation. Click the cancel button to stop running asynchronous operations. The result of each operation is displayed in MessageBox.

Visual Studio provides extensive support for this task.

 

Example:

Using system;
Using system. componentmodel;
Using system. drawing;
Using system. Threading;
Using system. Windows. forms;

Namespace backgroundworkerexample
{
Public class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}

Private void backgroundworker=dowork (Object sender, doworkeventargs E)
{
// Do not access the form's backgroundworker reference directly.
// Instead, use the reference provided by the sender parameter.
Backgroundworker BW = sender as backgroundworker;

// Extract the argument.
Int Arg = (INT) E. argument;

// Start the time-consuming operation.
E. Result = timeconsumingoperation (BW, ARG );

// If the operation was canceled by the user,
// Set the doworkeventargs. Cancel property to true.
If (bw. cancellationpending)
{
E. Cancel = true;
}
}

// This event handler demonstrates how to interpret
// The outcome of the Asynchronous Operation implemented
// In the dowork event handler.
Private void backgroundworkerappsrunworkercompleted (
Object sender,
Runworkercompletedeventargs E)
{
If (E. cancelled)
{
// The user canceled the operation.
MessageBox. Show ("operation was canceled ");
}
Else if (E. Error! = NULL)
{
// There was an error during the operation.
String MSG = string. Format ("an error occurred: {0}", E. Error. Message );
MessageBox. Show (MSG );
}
Else
{
// The operation completed normally.
String MSG = string. Format ("result = {0}", E. Result );
MessageBox. Show (MSG );
}
}

// This method models an operation that may take a long time
// To run. It can be canceled, it can raise an exception,
// Or it can exit normally and return a result. These Outcomes
// Are chosen randomly.
Private int timeconsumingoperation (
Backgroundworker BW,
Int sleepperiod)
{
Int result = 0;

Random Rand = new random ();

While (! Bw. cancellationpending)
{
Bool exit = false;

Switch (RAND. Next (3 ))
{
// Raise an exception.
Case 0:
{
Throw new exception ("an error condition occurred .");
Break;
}

// Sleep for the number of milliseconds
// Specified by the sleepperiod parameter.
Case 1:
{
Thread. Sleep (sleepperiod );
Break;
}

// Exit and return normally.
Case 2:
{
Result = 23;
Exit = true;
Break;
}

Default:
{
Break;
}
}

If (Exit)
{
Break;
}
}

Return result;
}

Private void startbtn_click (Object sender, eventargs E)
{
This. backgroundworker1.runworkerasync (2000 );
}

Private void cancelbtn_click (Object sender, eventargs E)
{
This. backgroundworker1.cancelasync ();
}

/// <Summary>
/// Required designer variable.
/// </Summary>
Private system. componentmodel. icontainer components = NULL;

/// <Summary>
/// Clean up any resources being used.
/// </Summary>
/// <Param name = "disposing"> true if managed resources shocould be disposed; otherwise, false. </param>
Protected override void dispose (bool disposing)
{
If (disposing & (components! = NULL ))
{
Components. Dispose ();
}
Base. Dispose (disposing );
}

# Region windows Form Designer generated code

/// <Summary>
/// Required method for designer support-do not modify
/// The contents of this method with the code editor.
/// </Summary>
Private void initializecomponent ()
{
This. backgroundworker1 = new system. componentmodel. backgroundworker ();
This. startbtn = new system. Windows. Forms. Button ();
This. cancelbtn = new system. Windows. Forms. Button ();
This. suspendlayout ();
//
// Backgroundworker1
//
This. backgroundworker1.workersuppscanscancellation = true;
This. backgroundworker1.dowork + = new system. componentmodel. doworkeventhandler (this. backgroundworker+dowork );
This. backgroundworker1.runworkercompleted + = new system. componentmodel. runworkercompletedeventhandler (this. backgroundworker1_runworkercompleted );
//
// Startbtn
//
This. startbtn. Location = new system. Drawing. Point (12, 12 );
This. startbtn. Name = "startbtn ";
This. startbtn. size = new system. Drawing. Size (75, 23 );
This. startbtn. tabindex = 0;
This. startbtn. Text = "start ";
This. startbtn. Click + = new system. eventhandler (this. startbtn_click );
//
// Cancelbtn
//
This. cancelbtn. Location = new system. Drawing. Point (94, 11 );
This. cancelbtn. Name = "cancelbtn ";
This. cancelbtn. size = new system. Drawing. Size (75, 23 );
This. cancelbtn. tabindex = 1;
This. cancelbtn. Text = "cancel ";
This. cancelbtn. Click + = new system. eventhandler (this. cancelbtn_click );
//
// Form1
//
This. autoscaledimensions = new system. Drawing. sizef (6f, 13f );
This. autoscalemode = system. Windows. Forms. autoscalemode. Font;
This. clientsize = new system. Drawing. Size (183, 49 );
This. Controls. Add (this. cancelbtn );
This. Controls. Add (this. startbtn );
This. Name = "form1 ";
This. Text = "form1 ";
This. resumelayout (false );

}

# Endregion

Private system. componentmodel. backgroundworker backgroundworker1;
Private system. Windows. Forms. Button startbtn;
Private system. Windows. Forms. Button cancelbtn;
}

Public class Program
{
Private Program ()
{
}

/// <Summary>
/// The main entry point for the application.
/// </Summary>
[Stathread]
Static void main ()
{
Application. enablevisualstyles ();
Application. Run (New form1 ());
}
}
}

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.