Unloading COM Objects C# [duplicate]
Possible Duplicate:
How to properly clean up Excel interop objects in C#
I am using EXCEL INTEROP for reading excel files in my .NET application. However I see that after am done with it, I still see the EXCEL.EXE in Windows Task Manager.
The code is as follows:
ApplicationClass excel = new ApplicationClass();
Workbooks workBooks = excel.Workbooks;
Workbook workBook = workBooks.Open(fileName,0,true,5,"","",true,XLPlatform.xlWindows,"\t",false,false,0,true,1,0);
foreach (Name name in workBook.Names)
{
try
{
// =#REF!#REF! indicates that the named range refers to nothing. Ignore the开发者_运维问答se..
if (name.Value != "=#REF!#REF!")
{
if (!retNamedRanges.ContainsKey(name.Name))
{
string keyName = name.Name;
object value = name.RefersToRange.get_Value(missing);
retNamedRanges.Add(keyName, value);
}
}
}
catch (Exception ex)
{
}
}
if(workBook!=null)
{
workBook.Close(false,missing,missing);
}
if(workBook!=null)
{
workBooks.Close();
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBooks);
workBook = null;
workBooks = null;
excel.Application.Quit();
excel.Quit();
excel = null;
I have tried to do all possible things to clean up, but still it does not go. There are multiple EXCEL files that I need to read. Typically after my application executes I see multiple instances of EXCEL.EXE.
Is there anything else am missing with the clean up?
Many thanks in advance
"Some process specific to my application I am doing..."
Actually, this is most likely where the problem lies. As in the referenced duplicate, if you reference a property of the ApplicationClass
then you'll need to make sure you dereference that property before the garbage collector will tidy up and remove Excel.
So, for instance, copy any data you need to string
, int
, etc. (or your own internal types based on these base types).
Try using Marshal.*Final*ReleaseComObject instead of ReleaseComObject. Also call it on your "ApplicationClass excel" instance.
精彩评论