10

I have a background worker. Before I invoke the worker I disable a button and make a gif visible. I then invoke the runworkerasync method and it runs fine until comleteion. On the 'RunWorkerCompleted()' I get a cross thread error. Any idea why?

    private void buttonRun_Click(object sender, EventArgs e)
    {
        if (comboBoxFiscalYear.SelectedIndex != -1 && !string.IsNullOrEmpty(textBoxFolderLoc.Text))
        {
            try
            {
                u = new UpdateDispositionReports(
                    Convert.ToInt32(comboBoxFiscalYear.SelectedItem.ToString())
                    , textBoxFolderLoc.Text
                    , Properties.Settings.Default.TemplatePath
                    , Properties.Settings.Default.ConnStr);
                this.buttonRun.Enabled = false;
                this.pictureBox1.Visible = true;

                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                bw.RunWorkerAsync();
                //backgroundWorker1.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to process.\nError:" + ex.Message, Properties.Settings.Default.AppName);
            }
        }
    }

    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        buttonRun.Enabled = true;
        pictureBox1.Visible = false;
    }

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        u.Execute();
    }
0

2 Answers 2

24

It seems to be an issue with VSTO and BackgroundWorker.

The solution is here.

Basically you need to call

System.Threading.SynchronizationContext.SetSynchronizationContext(new WindowsFormsSynchronizationContext());

before you call RunWorkerAsync. Works great.

To avoid instantiating the object every time you may have a static member in you AddIn's main class and reuse it. This way you only instantiate once.

3
  • 1
    This just saved my weekend.
    – squillman
    Dec 14, 2012 at 17:51
  • 1
    Saved me a few hours, too. May 6, 2015 at 9:52
  • 1
    Seriously ? Excellent tip, but finding that solution just killed most of my afternoon. I need a beer !! Oct 8, 2015 at 13:59
2

something about VSTO running the background worker on the same thread as the controls. Not sure. I had to check the InvokeRequired

    private void buttonRun_Click(object sender, EventArgs e)
    {
        if (comboBoxFiscalYear.SelectedIndex != -1 && !string.IsNullOrEmpty(textBoxFolderLoc.Text))
        {
            try
            {
                u = new UpdateDispositionReports(
                    Convert.ToInt32(comboBoxFiscalYear.SelectedItem.ToString())
                    , textBoxFolderLoc.Text
                    , Properties.Settings.Default.TemplatePath
                    , Properties.Settings.Default.ConnStr);
                this.buttonRun.Enabled = false;
                this.pictureBox1.Visible = true;

                BackgroundWorker bw = new BackgroundWorker();
                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
                bw.RunWorkerAsync();
                //backgroundWorker1.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to process.\nError:" + ex.Message, Properties.Settings.Default.AppName);
            }
        }
    }
    delegate void ReenableRunCallback();

    private void ReenableRun()
    {
        if (this.buttonRun.InvokeRequired)
        {
            ReenableRunCallback r = new ReenableRunCallback(ReenableRun);
            this.buttonRun.Invoke(r, null);
        }
        else
            this.buttonRun.Enabled = true;
    }
    private void HideProgress()
    {
        if (this.pictureBox1.InvokeRequired)
        {
            ReenableRunCallback r = new ReenableRunCallback(HideProgress);
            this.pictureBox1.Invoke(r, null);
        }
        else
            this.pictureBox1.Visible = false;
    }

    void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        ReenableRun();
        HideProgress();
    }

    void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        u.Execute();
    }
1
  • 2
    +1 Your button was initially created from your first and main thread of the application, also know as the GUI thread. Then, on RunWorkerCompleted, you try to access the button that has been created from previous thread. Then, you need to verify whether your button can be accessed with the InvoqueRequired property, then retrying through an invoed delegate as you did, this to synchronize both threads. That's the way! Mar 15, 2010 at 19:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.