C runs the operation of BackgroundWorker in the background

  • 2020-05-27 07:01:45
  • OfStack

In our program, often there will be more time-consuming long operations, to ensure that the user experience, not cause interface does not respond, we will use a multithreaded operations 1, let the time-consuming operation is completed, in the background again after the completion of processing or give hint, in operation, will always go to refresh the progress bar on display interface, when necessary to control the background thread interrupts the current operation.

Previously, similar applications were cumbersome, required a lot of code, and were prone to exceptions. In.net, a component is provided that BackgroundWorker specifically addresses this problem. The BackgroundWorker class allows operations to be run on a separate, dedicated thread. Time-consuming operations, such as downloads and database transactions, can cause the user interface (UI) to appear unresponsive when running for a long time. If you need a responsive user interface and face the long delays associated with such operations, you can easily use the BackgroundWorker class to solve the problem.

Using this component is actually quite simple. For example, let's make a small example of a progress bar similar to the following interface, running a time-consuming operation in the background thread while refreshing the progress bar on the interface.
The process is as follows:
1. Create a new windows forms application, such as BackgroundWorkerProgressBarDemo
2. Drag 1 ProgressBar(progressBar1) and 1 BackgroundWorker (backgroundWorker1) onto Form.
3. Pass the following code copy to ok. The code is commented in detail and can be modified as required.


namespace BackgroundWorkerProgressBarDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Shown += new EventHandler(Form1_Shown);
            // To report progress from the background worker we need to set this property
            backgroundWorker1.WorkerReportsProgress = true;
            // This event will be raised on the worker thread when the worker starts
            backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
            // This event will be raised when we call ReportProgress
            backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        }
        void Form1_Shown(object sender, EventArgs e)
        {
            // Start the background worker
            backgroundWorker1.RunWorkerAsync();
        }
        // On worker thread so do our thing!
        void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // Your background task goes here
            for (int i = 0; i <= 100; i++)
            {
                // Report progress to 'UI' thread
                backgroundWorker1.ReportProgress(i);
                // Simulate long task
                System.Threading.Thread.Sleep(100);
            }
        }
        // Back on the 'UI' thread so we can update the progress bar
        void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // The progress percentage is a property of e
            progressBar1.Value = e.ProgressPercentage;
        }
    }
}

To prepare for background operations, add an event handler for the DoWork event, where the time-consuming operation is invoked.

To start this operation, call RunWorkerAsync.

To receive notification of progress updates, process the ProgressChanged event.

To receive notification when the operation is complete, handle the RunWorkerCompleted event.

Note:

You must be very careful not to manipulate any user interface objects in the DoWork event handler. Instead, you should communicate with the user interface through ProgressChanged and RunWorkerCompleted events.

The BackgroundWorker event is not marshaled across the AppDomain boundary. Please do not use the BackgroundWorker component to multithread multiple AppDomain operations.

If the background operation requires parameters, give them when calling RunWorkerAsync. Within the DoWork event handler, this parameter can be extracted from the DoWorkEventArgs.Argument property.


Related articles: