This project has moved. For the latest updates, please go here.

How to correctly dispose excel when using multiple threads?

Mar 5, 2014 at 8:14 PM
First of all many thanks for such amazing project!!!

I'm new to NetOffice and also ExcelDNA, anyway I've createad a small DNA addin that performs a long operation, hence I need to run it in a parallel thread. If I perform such an operation then Excel process does not exit when user tries to close it.

in my code I'm using this
using (new ExcelSynchronizationContextInstaller())
                _isRunning = true;
                var ctx = SynchronizationContext.Current;
                Task.Factory.StartNew(() =>
                        catch (Exception e)
                            ctx.Post(_ =>
                                _isRunning = false;
                            }, null);
ExcelSynchronizationContextInstaller comes from here

My cleanup routine is following (executed within ExcelRibbon.OnBeginShutdown override)
if (_excel == null) return;
var x = Factory.ProxyCount;
x = Factory.ProxyCount; //==1
x = Factory.ProxyCount;//==1
x = Factory.ProxyCount; //==0
_excel = null;            
x = Factory.ProxyCount;//==0
When I don't use the ExcelSynchronizationContextInstaller e.g. when the action() is executed on the "primary" thread, then Excel exits as expected.

Is there any recommended/preffered way how to perform long operation in another thread?

Also does the Application.DisposeChildInstances() dispose all referenced workbooks?

Many thanks in advance
Mar 11, 2014 at 3:17 PM
From an Excel-DNA add-in, I suggest you never call back to Excel from another thread or Task. When you need to update Excel, just call the Excel-DNA helper ExcelAsyncUtil.QueueAsMacro with a delegate that does the Excel-related work. This delegate will then run on the main Excel thread, and you won't need any COM cleanup code anywhere.