Background RunworkerCompleted Event not firing on VSTA_Main Thread : Excel VSTO Addin

722 views Asked by At

I'm working on a VSTO-addin for excel where i've deployed a background worker to do some task. I need to update some content on the sheet once background worker completes it's exceution. I'm using Background RunworkerCompleted Event to do this task once background worker is done with its task. According to the posts below :

it is mentioned that Background RunworkerCompleted Event is fired on the UI Thread if the BackgroundWorker was created on the UI Thread. I've deployed my background worker on the VSTA_Main thread provided by the addin but the Background RunworkerCompleted Event associated with it is getting fired on an arbitrary worker thread. I have following doubts regarding this problem :

  1. Is VSTA_Main thread different from the UI thread of excel ? (i think it is, but i just wanted to confirm)

  2. How can I manage the thread deployment by using synchronizationcontext (or any other possible approach) so that the Background RunworkerCompleted Event is fired on the desired thread.

The simplified code in my case looks something like this :

// This code piece executes on VSTA_Main thread 

private BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
backgroundWorker.RunWorkerAsync();


// This code piece executes on some random worker thread - Assume Thread 1

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    // It simulates some task
    Thread.sleep(100) 
}


// This event is raised on a random worker thread - Not Thread 1 and not VSTA_Main

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // perform some sheet update operations
}

I'm currently working on Microsoft Visual Studio 2010 and Microsoft Excel 2007.

1

There are 1 answers

0
0xced On
  1. Is VSTA_Main thread different from the UI thread of excel ? (i think it is, but i just wanted to confirm)

I'm not sure about that (I found this question by googling VSTA_Main) but from my understanding, accessing UI elements in a VSTO addin must be done on this VSTA_Main thread.

  1. How can I manage the thread deployment by using synchronizationcontext (or any other possible approach) so that the Background RunworkerCompleted Event is fired on the desired thread.

It seems to be a bug in VSTO, here is a workaround: BackgroundWorker Not working in VSTO.