Quantcast
Channel: NetOffice - MS Office in .NET
Viewing all articles
Browse latest Browse all 1741

New Post: How to correctly dispose excel when using multiple threads?

$
0
0
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

Viewing all articles
Browse latest Browse all 1741

Trending Articles