You remember BackgroundWorker?

Source: Internet
Author: User

Turn on the computer, suddenly remembered, yesterday afternoon, a man and I discussed a matter, may take to say.

She says she's got a bunch of stuff to deal with, a progress bar, but the progress bar is in another window, and her idea is to start working on the data by popping up the progress dialog box, displaying the processing progress in real time, and closing the dialog box when the process is complete. At first glance it is not difficult, but she encountered the following problems, so in the group to ask questions.

1, modal dialog box problems.

This problem is good to do, in general, to deal with the data for a long time, should be considered in the background asynchronous operation, the brick home is multithreading. But she called the ShowDialog method when the window was displayed, so the code would stop there until the window closed.

If it is asynchronous operation, usually, after starting the background task will return immediately, so, as long as the order of the code can solve the problem, start the background task, and then call the ShowDialog method, so that Even if the code stops at ShowDialog, it does not affect the execution of background tasks.

2. How to control the controls in other windows.

You can define a public method in a window class to do something with the control, which can then be regulated elsewhere by these public methods. If it is called across threads, you should consider using a delegate or event to invoke it. How else did you learn to entrust and do things?

Alternatively, the ProgressBar control in the progress window is declared public so that other classes can be easily accessed.

3, background task how simple.

The method is flexible and has many kinds. The simplest is to take advantage of the new features in. NET 4.5 and C # 5.0, which is certainly the simplest. The second is to use the new task class in. NET 4 to dispatch threads; more traditionally, the most frequently used method in the 2.0 era is the direct use of the thread class.

However, there is a component that is designed for background tasks and is open, forget it? --backgroundworker, maybe some friends forgot about this component. Now a lot of people are like this, with the oversees wife, we have a large number of code farmers, often forget.

Is it not more appropriate to have a background task and report progress, with BackgroundWorker? So I asked her two times: "Remember?" "Really not what I expected, remember, hehe."

Having said so much, estimating the need for an example to solve the problem, well, serve the dishes.

Using System;  
Using System.Collections.Generic;  
Using System.ComponentModel;  
Using System.Data;  
Using System.Drawing;  
Using System.Linq;  
Using System.Text;  
Using System.Threading.Tasks;  
Using System.Windows.Forms;  
      
Using System.IO; namespace MYAPP {public partial class Form1:form {static string savedir = String.  
        Empty;  
        Private formprogress Fpro = null;  
            Public Form1 () {InitializeComponent ();  
        Fpro = new Formprogress ();  
            } private void Backgroundworker1_dowork (object sender, DoWorkEventArgs e) {  
            int filecount = Convert.ToInt32 (e.argument);  
            Random rand = new Random ();  
            byte[] buffer = new byte[2048]; for (int i = 0; i < FileCount; i++) {try {Strin  
  G FileName = Path.Combine (Savedir, i.tostring () + ". tmp");                  using (var stream = File.create (fileName)) {int n = 0;  
                        int maxbyte = 8 * 1024 * 1024; while (n < maxbyte) {rand.  
                            Nextbytes (buffer); Stream. Write (buffer, 0, buffer.)  
                            Length); n + = buffer.  
                        Length;  
                catch {continue; finally {//Report Progress This.ba  
                Ckgroundworker1.reportprogress (i + 1);  
            }} private void Button1_Click (object sender, EventArgs e) {  
            if (directory.exists (savedir) = = False) {return; } ButtOn1.  
            Enabled = false;  
            int cout = Convert.ToInt32 (This.nmbud.Value);  
            This.fpro.progressBar1.Minimum = 0;  
            This.fpro.progressBar1.Maximum = cout;  
            This.fpro.progressBar1.Value = This.fpro.progressBar1.Minimum;  
            This.backgroundWorker1.RunWorkerAsync (cout); ShowDialog//After starting an asynchronous operation this does not affect the execution fpro of the background task even if the code is parked there.  
        ShowDialog (this);  
            } private void Backgroundworker1_progresschanged (object sender, ProgressChangedEventArgs e) {  
            int val = e.progresspercentage; This.fpro.lblText.Text = string. Format ("{0} files have been generated.")  
            ", Val);  
        This.fpro.progressBar1.Value = val;  
        } private void Backgroundworker1_runworkercompleted (object sender, Runworkercompletedeventargs e) {button1.  
            Enabled = true; Fpro.  
            Hide (); MessageBox.Show ("Operation complete.") "," prompted ", MessageBoxButtons.OK, messageboxicon.information);  } private void Btnbrowsfd_click (object sender, EventArgs e) {FolderBrowserDialog  
            FD = new FolderBrowserDialog (); Fd.  
            RootFolder = Environment.SpecialFolder.Desktop; if (DialogResult.OK = = FD. ShowDialog ()) {Savedir = fd.  
            SelectedPath; } FD.  
        Dispose (); }  
    }  
}

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.