1

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();
    }
Sumeet Vishwas
  • 585
  • 1
  • 6
  • 18
  • 1
    Have you looked at this question? http://stackoverflow.com/questions/1111369/how-do-i-create-and-show-wpf-windows-on-separate-threads – Bill Berry Jun 20 '15 at 05:55
  • @BillBerry i have seen that, but its not beneficial to me. I need to open another window in same thread. I use basic thread but it not working then i use backgroundworker and it also creating problems – Sumeet Vishwas Jun 20 '15 at 06:12

2 Answers2

6

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(...)

Denis Yarkovoy
  • 1,277
  • 8
  • 16
  • i have tried, h1 = new IDesignSpecWord2007.UI_Forms.HierarchyView(ref Globals.ThisAddIn.Application, ref docm); h1.BeginInvoke(new Action(() => { h1.Show(); })); but its not working. window is not opening – – Sumeet Vishwas Jun 20 '15 at 07:53
  • No, you have to call BeginInvoke from your main form, not from the new form you are creating. Kindly re-read my answer, it mentions this at the end: ... you will need to explicitly specify the instance of your main form: mainFormInstance.BeginInovoke(...) – Denis Yarkovoy Jun 20 '15 at 16:47
0

You can use Dispatcher to ask UI thread to open dialog: (from here)

this.Dispatcher.BeginInvoke(new Action(() => ProgressDialog.ShowDialog()));
Community
  • 1
  • 1
farid bekran
  • 2,684
  • 2
  • 16
  • 29