在完成的方法中在后台worker和showdialog中加载新表单

时间:2016-12-17 12:12:12

标签: c# winforms

我想在后台加载新表单并在加载后显示它。 但我总是得到这个错误:“无效的跨线程访问”,代码位于: 如何使它工作?!

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();
    }

}

1 个答案:

答案 0 :(得分:0)

您可能必须将表单的数据加载和表单UI初始化分成两个不同的faze。

我已将您的代码示例更改为以下内容。

  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;
            }

        }