Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSTO: invoking on main Excel thread

Tags:

I have a button on an Excel sheet which starts a new thread to do some processing. If I want to make any changes to Excel (e.g. write data to a cell using Worksheet.Range("A1").Value = "info";), I think I must use the main UI thread.

How can this be done?

Typically in Winforms I would call Invoke on a control, but the Excel.Application or Worksheet or Range objects don't have an Invoke method.

like image 233
Laurent Avatar asked Apr 06 '11 14:04

Laurent


1 Answers

That work doesn't 'need' to be done on the UI thread, .net will marshal the call for you, but if you make repeated calls from a background thread you may hit performance issues.

But to answer your question specifically, if you have .net 3.5, in your add-in load event add this:

Dispatcher _dispatcher = Dispatcher.CurrentDispatcher; 

And then add:

public Dispatcher Dispatcher { get {return _dispatcher;} } 

Then you can dispatch to the UI thread by going

Globals.ThisAddIn.Dispatcher.Invoke(()=>{/*stuff*/}); 

If you don't have .net 3.5, then there are a few other thread synchronisation techniques, like using SynchronizationContext.Current instead of the Dispatcher.

like image 98
Jake Ginnivan Avatar answered Oct 05 '22 06:10

Jake Ginnivan