Will be all unmanaged COM objects released in case if I use code like this
var worksheet = new Application().Workbooks.Add().Worksheets.Add();
Marshal.ReleaseComObject(worksheet);
instead of code like this
var excel = new Application();
var workbook = excel.Workbooks.Add();
var worksheet = workbook.Worksheets.Add();
Marshal.ReleaseComObject(excel);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(worksheet);
?
If there is some documentation please send a link in answer.
Actually, both code samples will leave an Excel process running in the background. You need to call
Application.Quit()on the application object, for example. The following works:A few other good things to remember: I didn't use it here, but there's a Marshal.FinalReleaseComObject method that's very useful in these cases. Also, again I didn't use this in my code sample, but the
Marshal.ReleaseComObjectmethod returns the current count, so you could always do the release in a loop if you wanted to make sure the count reached zero:You can also use this for debugging purposes - e.g.