Home » excel » c# – Why is my Excel office object leaving behind EXCEL.exe processes?

c# – Why is my Excel office object leaving behind EXCEL.exe processes?

Posted by: admin April 23, 2020 Leave a comment


Possible Duplicate:
How to properly clean up Excel interop objects in C#

I have an application that uses Office Interop libraries for C#.

This library is called from an ASP.NET application hosted with IIS7.

The relevant code bits are:

/// <summary>
/// Provides excel functions.
/// </summary>
public class ExcelStuff : IDisposable
    #region Excel Components

    // The following are pre-allocated Excel objects that must be explicitly disposed of.

    private Excel.Application xApp;
    private Excel.Workbooks xWorkbooks;
    private Excel.Workbook xWorkbook;
    private Excel.Sheets xWorksheets;
    private Excel.Worksheet xWorksheet;
    private Excel.ChartObjects xCharts;
    private Excel.ChartObject xMyChart;
    private Excel.Chart xGraph;
    private Excel.SeriesCollection xSeriesColl;
    private Excel.Series xSeries;


    /// <summary>
    /// Initializes a new instance of the <see cref="ExcelStuff" /> class.
    /// </summary>
    public ExcelStuff()

    /// <summary>
    /// Does some work.
    /// </summary>
    public void DoWork()
        byte[] data = new byte[0];

        worker = new Thread(() =>
            // Do some work.


        worker = null;


    /// <summary>
    /// Disposes the current object and cleans up any resources.
    /// </summary>
    public void Dispose()
        // Cleanup

        // Manual disposal because of COM
        xApp = null;
        xWorkbook = null;
        xWorksheets = null;
        xWorksheet = null;
        xCharts = null;
        xMyChart = null;
        xGraph = null;
        xSeriesColl = null;
        xSeries = null;


You will notice a lot of redundancies in the code, which are my desperate attempt to solve this problem. So please don’t tell me that it’s inefficient to call GC.Collect() or that calling Dispose() from within the class isn’t good – I know these things already.

What I would like to know is, why this code keeps orphaned EXCEL.exe processes running on the server when I’m doing my best to clean up as many objects as possible.

How to&Answers:

As someone mentioned in a comment, Marshal.ReleaseComObject is what I use to clean up excel objects. Here is a sample of my code:

        wb.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);

        while (System.Runtime.InteropServices.Marshal.ReleaseComObject(wb) != 0)
        { }


        while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp) != 0)
        { }

This seems to work for me. Good luck!

EDIT: Sorry, didn’t see this was a dup. Mods can do whatever with this…