How to terminate C# based Excel Application instance?

前端 未结 2 735
盖世英雄少女心
盖世英雄少女心 2021-01-24 19:47

I\'m working on a small code to read some Excel files. I\'ve linked the COM library for Excel 15, and am using the following code to read Excel files:

excelInsta         


        
2条回答
  •  醉梦人生
    2021-01-24 20:26

    Disposing the Excel COM objects can be a bit finicky. Make sure you're calling Close on your Workbook when finished, and Quit on your instance of Excel.Application.

    Release the objects by calling FinalReleaseComObject(), and for redundancy, explicitly null the COM objects:

    Runtime.InteropServices.Marshal.FinalReleaseComObject(sheet);
    Runtime.InteropServices.Marshal.FinalReleaseComObject(workbook);
    Runtime.InteropServices.Marshal.FinalReleaseComObject(app);
    
    
    sheet = null;
    workbook = null;
    app = null;
    

    Lastly, if the buggers still don't seem to go away after calling the appropriate disposal methods, explicitly releasing them, and nulling the references to the objects , call the Garbage Collector:

    GC.Collect();
    GC.WaitForPendingFinalizers();
    

    And hopefully that will finally do it.

    Cheers.

    Edit: Also, be sure to do this in an exception handler if there's a chance your code will bomb while you're using the Interop objects, or because of them. You'll leave zombie processes even if the parent terminates.

提交回复
热议问题