I am creating a Forms application using C# and the Interop.Excel library to read and write data to an Excel spreadsheet. There is a problem where Excel will spawn processes, but they won't close even after I call the function that should close it. Here is an example of my code handling closing of the Excel application:
var excel = new Microsoft.Office.Interop.Excel.Application();
var workbooks = excel.Workbooks;
Workbook workbook = null;
Worksheet worksheet = null;
[insert code here where all the Excel spreadsheets are properly imported and exported ect]
workbook.Save();
workbook.Close(0);
workbooks.Close();
excel.Quit();
I remember that the majority of answers I found online to my problem recommended that I use Marshal.ReleaseComObject(excel); or something to that effect. However, I also found that Microsoft considers Marshal.ReleaseComObject dangerous and recommends not to use it.
Is there a safe way to use Marshal.ReleaseComObject? Or is there another solution to my problem?