Excel interop, gcHandle and closing Excel RRS feed

  • Question

  • Hi,

    I am using C#.net using interop to read to and write from Excel and I am having trouble closing Excel after using it.

    I have had this issue on and off for years, but it was under control until I upgraded to Windows 10, Excel  365/2016, Visual Studio 15.8.1, and Microsoft.Office.Interop.Excel.15.0.4795.1000.  I now seem to be completely unable to close an Excel process after it has been opened.

    I open Excel as follows:

      	 GCHandle rcwHandle;
            _App = new Microsoft.Office.Interop.Excel.Application();
            rcwHandle = GCHandle.Alloc(_App, GCHandleType.Normal);

    but rcwHandle does NOT get allowcated! It is always rcwHandle.IsAllocated==false and it is not initialized.

    I (try to) dispose Excel as follows:

         if (disposing)
                    if (_App != null &&rcwHandle.IsAllocated)
                        _App.DisplayAlerts = false;
                        for (int bookCount = _App.Workbooks.Count; bookCount > 0; bookCount--)
                            Workbook book = _App.Workbooks[bookCount];
                            for (int sheetCount = book.Sheets.Count; sheetCount > 0; sheetCount--)
                                Worksheet sheet = (Worksheet)book.Sheets[sheetCount];
                                sheet = null;
                            book = null;
                        _App = null;

    The main section of this does not ever get called as rcwHandle.IsAllocated is false. I tried removing the requirement for rcwHandle.IsAllocated to enter then main section, but Excel processes stayed open even with all that marshalling and releasing.

    I don't really understand garbage collection and interop, so I don't know what to try next. I would appreciate any help.



    Ethan Strauss

    Monday, August 27, 2018 9:25 PM

All replies

  • Hi Ethan Strauss,

    Thank you for posting here.

    Since your question is more related to office, you could post a new thread in Excel for Development forum for suitable support.


    The Visual C# forum discuss and ask questions about the C# programming language, IDE, libraries, samples, and tools.

    Best Regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, August 28, 2018 6:49 AM