This project has moved and is read-only. For the latest updates, please go here.

How to correctly dispose excel when using multiple threads?

Mar 5, 2014 at 9: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;
                UpdateViews();
                var ctx = SynchronizationContext.Current;
                Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            action();
                        }
                        catch (Exception e)
                        {...}
                        finally
                        {
                            ctx.Post(_ =>
                            {
                                _isRunning = false;
                                UpdateViews();                           
                            }, null);
                        }
                    });
            }
ExcelSynchronizationContextInstaller comes from here

My cleanup routine is following (executed within ExcelRibbon.OnBeginShutdown override)
if (_excel == null) return;
var x = Factory.ProxyCount;
_excel.DisposeChildInstances();
x = Factory.ProxyCount; //==1
_excel.Quit();
x = Factory.ProxyCount;//==1
_excel.Dispose();
x = Factory.ProxyCount; //==0
_excel = null;            
Factory.DisposeAllCOMProxies();
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 4: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.

-Govert