简体   繁体   中英

how to open another window form in backgroundworker in c#

i need to run a time consuming process in backgroundworker and in that process i need to open a window too. All work good but when i call a UI in that process, it not allow me to work in that new window it just show waiting and when i cancel the backgroundworker process it not cancel either although i enable workersupportcancel. Here is my code

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        runCheck();    
    }

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            MessageBox.Show(e.Error.Message);
        }           
    }
    private void newBtncheck_Click(object sender, RibbonControlEventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }       

 private void newBtncheck_Click(object sender, RibbonControlEventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
    }
    private void btnStop_Click(object sender, RibbonControlEventArgs e)
    {
        this.backgroundWorker1.CancelAsync();
    }

You need to wrap your code that opens new form in the BeginInvoke() of the calling form.

Put this in your backgroundWorker1_DoWork() method:

BeginInvoke(new Action(()=>{ 
  // place code to open new form here, for example new MyNewForm().Show()
}));

This is assuming your backgroundWorker1_DoWork() is a member of your main form class. If not, you will need to explicitly specify the instance of your main form: mainFormInstance.BeginInovoke(...)

您可以使用Dispatcher要求UI线程打开对话框:(从此处开始

this.Dispatcher.BeginInvoke(new Action(() => ProgressDialog.ShowDialog()));

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