none
Issue calling Globals.Factory.GetVstoObject(...) from a Thread. Always returns null. RRS feed

  • Question

  • Hi everyone,

    I´m developing a Document-level Add-in for Excel using C#, .NET 4.0 and VSTO 2010.

    I have some VSTO buttons added to the worksheet and a thread running in background updating the color and text of the buttons.

    In order to update  the buttons, first I have to get the references of each button and then update them.

    Well, my problem is that the method Globals.Factory.GetVstoObject(...) always returns null, and it shouldnt because when i call it out of the thread it returns the right reference of the button.

    //Get the Excel Worksheet Excel.Worksheet w = Globals.ThisWorkbook.Worksheets[sheet]; //Get the Extended VSTO Worksheet //ALWAYS return null VSTO.Worksheet ws = Globals.Factory.GetVstoObject(w); //this is the button VSTO.Controls.Button b = null; if (ws.Controls.Contains(name)) { b = (VSTO.Controls.Button)ws.Controls[name];

    //Update Button

    b.text = ...

    b.color = ... }


    I hope someone can help me.

    Tahnk you very much in advance.

    cocoVSTO.

    Wednesday, June 13, 2012 5:30 PM

Answers

  • you must never ever use office API (also vsto) from another thread than man UI thred (thread where your add-in's startup event was called on). You can span background threads to do some processing, communication, etc.  but to modify office (change buttons, modify range, cells, etc) you must always synchronize to that main thread. You can achieve this by storing somewehre WinFormsSynchronizationContext that you initalize in your startup event and call either Post or Send on it when you want to modify something in office from background thread.
    • Marked as answer by cocoVSTO Wednesday, June 13, 2012 11:22 PM
    Wednesday, June 13, 2012 6:24 PM
    • Marked as answer by cocoVSTO Wednesday, June 13, 2012 11:22 PM
    Wednesday, June 13, 2012 8:14 PM

All replies