Search code examples
c#wpfmultithreadingexcel-dnac-api

ExcelDna C API calls from asynchronous WPF window running in a different thread than Excel


I have an asynchronous WPF window running over Excel in a separated thread. I'm trying to use C API calls, embedded in ExcelDna.Utilities library to access heavy amounts of data spread over various Excel workbooks/spreadsheets.

Any call I try throws an error, that I'm supposing its because it is running in a different thread and does not access the Excel running thread to get its Application object.

When I try to do the same through a macro (a c# method called by ribbon button ) it works with no problem. That is the first clue to make sure its a thread problem.

I'm a newbie in multi-threading, but as far as I know, I should call it from the Dispatcher object. The problem is that I can't figure out a way to do that.

Are my suppositions correct, or there is another thing I'm just overlooking? If so, how to access ''ExcelDna.Utilities.XLApp'' from Dispatcher?

ExcelDna.Utilities.Workbook[] workbooks = ExcelDna.Utilities.XLApp.Workbooks;

By the way, Office.Interop works in the window thread, but it is not an option for me.


Solution

  • You can schedule code to run on the main thread, in a macro context where the C API is safe to call, with the Excel-DNA helper ExcelAsyncUtil.QueueAsMacro.