If the form is closed when the BackgroundWorker is running

Source: Internet
Author: User

In Windows Form applications, the BackgroundWorker class allows you to run operations on individual dedicated threads. Time-consuming operations (such as downloads and database transactions) may cause the user interface (UI) to stop responding after a long time of running. You can use the BackgroundWorker class to solve the problem easily if you need a user interface that can respond and face long delays related to such operations. Because the operation is performed asynchronously, you may close the current form during the asynchronous operation, and the closure of the form is accompanied by the execution of the Dispose method. If we have registered the RunWorkerCompleted event of BackgroundWorker and need to operate the Disposed form in the event handler, some unpredictable exceptions will occur.

1. A simple example

Let's write a simple example to illustrate the above scenario: In a non-main form (the closure of the main form will lead to the termination of the program) Windows form, A BackgroundWorker is used to perform a time-consuming operation asynchronously. In our example, we simulate this "time-consuming operation" by letting the thread sleep for 10 seconds ". Method: backgroundWorker_RunWorkerCompleted is the method for handling the RunWorkerCompleted event of BackgroundWorker. Here we use MessageBox to display the IsDisposed attribute value of the current form. The Asynchronous Operation registered to this BackgroundWorker is enabled by clicking a button. The related code is as follows.

   1: public partial class BgwForm : Form
   2: {
   3:     public BgwForm()
   4:     {
   5:         InitializeComponent();
   6:     }
   7:  
   8:     private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
   9:     {
  10:         Thread.Sleep(10000);
  11:     }
  12:  
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.