简体   繁体   中英

Load new form in background worker and showdialog in completed method

I want to load new form in background and show it after loaded. but I always got this error : "invalid cross-thread access" with the code under: How to make it work?!

public partial class f1 : Form
{
    private Form f2;
    public f1()
    {
        InitializeComponent();
        BackgroundWorker bgw = new BackgroundWorker();
        bgw.RunWorkerAsync();
        bgw.DoWork += new DoWorkEventHandler(dowork);
        bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completed);
    }
    void dowork(object sender, DoWorkEventArgs e)
    {
        f2 = new f2();
    }

   void completed(object sender, RunWorkerCompletedEventArgs e)
    {
        f2.showdialog();
        this.Close();
    }

}

you may have to separate the data loading for form and form UI initialization into two different faze.

I have changed your code sample to the following.

  public partial class Form2 : Form
        {
            public Form2()
            {
                InitializeComponent();

                BackgroundWorker bgw = new BackgroundWorker();
                bgw.RunWorkerAsync();
                bgw.DoWork += new DoWorkEventHandler(dowork);
                bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(completed);
            }
            void dowork(object sender, DoWorkEventArgs e)
            {    
                e.Result = InitializeNeededDataToShowOnTheSecondform();
            }


            void completed(object sender, RunWorkerCompletedEventArgs e)
            {
                BeginInvoke(new MethodInvoker(() =>
                {
                    var f2 = new Form3(e.Result);
                    f2.ShowDialog();
                    this.Close();

                }));
            }

            private object InitializeNeededDataToShowOnTheSeconDform()
            {
//time consuming data initialization and/or any other time consuming process
                return 10;
            }

        } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM