Asynchronously load data in WinForm and use the progress bar. winform progress bar

Source: Internet
Author: User

Asynchronously load data in WinForm and use the progress bar. winform progress bar

In the WinForm program, the UI may be suspended due to loading a large amount of data, which is unfriendly to users. Therefore, when loading a large amount of data, you should first load the data in another thread to ensure the UI interface response; next, you can provide a progress bar to understand that the program is loading data and the current loading progress.

One simple way to implement the above functions is to use System. tool class in ComponentModel: BackgroundWorker, which supports cancelling, progress reporting, and exception forwarding, and implements the IComponent interface, which means that it can be dragged directly from the toolbox in the VS designer to the interface.

The following example shows how to use BackgroundWorker. For more information about BackgroundWorker, see Threading in C # (or Chinese translation ):

1. Add a progress bar, a start button, an end button, and a BackgroundWorker on the UI, and set the following BackgroundWorker attributes (in this example, the Name is bw ):

 

  • WorkerReportsProcess: The default value is False. Set this parameter to True. Progress reports are supported.
  • Workersuppscanscancellation: The default value is False. Set this parameter to True. cancellation is supported.

2. DoWork event: Execute data loading in it, and execute a loop to simulate data loading.

Private void bw_DoWork (object sender, DoWorkEventArgs e) {var count = (int) e. argument; for (int I = 1; I <= count; I ++) {if (bw. cancellationPending) {e. cancel = true; return;} bw. reportProgress (I); Thread. sleep (200); // simulate time-consuming tasks }}
  • Note: The UI control cannot be updated in this method.
  • Check CancellationPending to determine whether the cancellation is performed.
  • Report progress by calling ReportProgress

 

3. ProgressChanged event, where you can operate the progress bar and other UI controls.

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e){    progressBar.Value = e.ProgressPercentage;    resultTextBox.Text += DateTime.Now + "\r\n";}

Use e. ProgressPercentage to obtain the progress set during task execution and update the progress bar.

4. The RunWorkerCompleted event, where you can update the UI and handle exceptions.

Private void bw_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e) {if (e. Cancelled) resultTextBox. Text + = "the task is canceled. "+" \ R \ n "; else if (e. Error! = Null) resultTextBox. Text + = "An exception occurred:" + e. Error + "\ r \ n"; else resultTextBox. Text + = "the task is completed. "+" \ R \ n ";}

When an exception occurs during execution, the exception will be forwarded to this place, so you can handle the exception here.

5. Use a start button and a Cancel button to control:

  • Bw. RunWorkerAsync () Startup
  • Bw. CancelAsync () canceled

The complete code and output are as follows:

Public partial class Form1: Form {public Form1 () {InitializeComponent (); bw. doWork + = bw_DoWork; bw. progressChanged + = bw_ProgressChanged; bw. runWorkerCompleted + = bw_RunWorkerCompleted;} private void startButton_Click (object sender, EventArgs e) {progressBar. value = 0; progressBar. maximum = 10; resultTextBox. text = "task start... "+" \ r \ n "; bw. runWorkerAsync (10);} private void bw_DoWork (object send Er, DoWorkEventArgs e) {var count = (int) e. argument; for (int I = 1; I <= count; I ++) {if (bw. cancellationPending) {e. cancel = true; return;} if (I = 2) throw new Exception ("error! "); Bw. reportProgress (I); Thread. sleep (200) ;}} private void bw_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e) {if (e. cancelled) resultTextBox. text + = "the task is canceled. "+" \ R \ n "; else if (e. Error! = Null) resultTextBox. Text + = "An exception occurred:" + e. Error + "\ r \ n"; else resultTextBox. Text + = "the task is completed. "+" \ R \ n ";} private void bw_ProgressChanged (object sender, ProgressChangedEventArgs e) {progressBar. value = e. progressPercentage; resultTextBox. text + = DateTime. now + "\ r \ n";} private void cancelbutton_Click (object sender, EventArgs e) {bw. cancelAsync ();}}

The output is as follows:

 

Reference: Threading in C # --> Chinese Translation

Related Article

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.