C # small example of backgroundworker multi-thread operations

Source: Internet
Author: User

In ourProgramIn, there are often some time-consuming operations. To ensure the user experience, do not cause the interface to not respond, we generally use multi-threaded operations, so that time-consuming operations are completed in the background, after the process is completed, or a prompt is displayed. During running, the progress bar and other display elements on the interface will be refreshed from time to time. If necessary, the background thread must be controlled to interrupt the current operation.

In the past, similar applications were troublesome and needed to be written.CodeMany, but also very prone to exceptions. In. Net, a backgroundworker component is provided to solve this problem.

This component is actually very simple. For example, we will make a small example of a progress bar similar to the following interface, perform time-consuming operations in the background thread, and refresh the scroll bar and prompt information on the interface, the processing result is displayed.

Drag the backgroundworker component into the interface and respond to the three events.

The Code is as follows:

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;

Small Example of multiple threads in namespace
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}

// The response message is used to process the display of the interface.

Private void backgroundworker1_progresschanged (Object sender, progresschangedeventargs E)
{
This. progressbar1.value = E. progresspercentage;
This. label1.text = E. userstate. tostring ();
This. label1.update ();
}

// Here is the message processing after the background work is completed. You can perform subsequent processing here.

Private void backgroundworkerappsrunworkercompleted (Object sender, runworkercompletedeventargs E)
{
MessageBox. Show ("Operation completed ");
}

// This is where the working function is called when the background process starts to work. You can write your existing processing functions here.

Private void backgroundworker=dowork (Object sender, doworkeventargs E)
{
Work (this. backgroundworker1 );
}

// Real Processing

private bool work (backgroundworker BK)
{< br> int tatle = 10000;

for (INT I = 0; I {< br> If (BK. cancellationpending) // determine whether the user needs to cancel the background and exit as soon as possible.
{< br> BK. reportprogress (I, String. format ("the current value is {0}, the operation is interrupted by user application", I);
return false;
}

// Report the processing progress to the main thread through this function during processing. It is best to convert the progress to a percentage, which must correspond to the maximum value of the progress bar outside. Here, I did not translate, but adjusted the maximum progress bar value of the interface thread to be consistent with the total number here.
BK. reportprogress (I, String. Format ("the current value is {0}", I ));
}
Return true;
}

Private void button2_click (Object sender, eventargs E)
{

// When the user asks to cancel the operation, it will be handled in this way. Sometimes it's not so clever.

This. backgroundworker1.cancelasync ();
}

Private void button#click (Object sender, eventargs E)
{

// This is to start background work.

This. backgroundworker1.runworkerasync ();
}

Private void button3_click (Object sender, eventargs E)
{
This. Close ();
}
}
}

 

Generally, you can simply handle it like this. If multiple threads need to interact or share data ,. net C # still provides system. threading. thread class, which is no big difference from traditional usage and is also quite useful.

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.