As we all know, in the. NET world, programmers are only responsible for creating objects using new, and the destruction of objects is entirely left to the garbage collector, and only types in. NET are destroyed when garbage collection occurs. This usually does not cause any impropriety. However, when you use an unmanaged COM object, you can create a particular problem.
COM uses reference counting to determine the lifetime of an object, and COM clients call IUNKNOWN->ADDREF () each time they refer to the object, and each time the object is released, Iunknown->release () is invoked, and once the reference count reaches 0, Releases the instance. So the problem arises, let's look at the following code:
This is a widely circulated section of the ASP.net version of CSDN. C # code to export an Excel file to a client using an Excel COM component, and the wizard to add a COM reference was run before this code was added.
Excel.Application oexcel;
Excel.Workbook obook;
Object omissing = System.Reflection.Missing.Value;
oexcel = new Excel.Application ();
obook = OExcel.Workbooks.Add (omissing);
for (int i=1;i <=4;i++)
{
Oexcel.cells[i,1]=i.tostring ();
oexcel.cells[i,2]= "' Bbb2";
oexcel.cells[i,3]= "' ccc3";
oexcel.cells[i,4]= "' Aaa4";
}
Obook.saved = true;
oExcel.UserControl = false;
string filename = DateTime.Now.Ticks.ToString ();
String Mm=server.mappath (".") + "\" + filename + ". xls";//Server Save Address
OExcel.ActiveWorkbook.SaveCopyAs (mm);
oExcel.Quit ();
Gc. Collect ();
Response.Redirect (filename+ ". xls");
This code will enable you to export the file, but if you look at Windows Task Manager, you'll find the highlights of the following image
So someone adds a "GC" to the code. Collect (); ", very well, EXCEL. EXE not so much, as the following figure.
But how can it be completely released?
Fortunately, In. NET, allows programmers to explicitly invoke COM's release method, which passes through the. NET wrapper, called System.Runtime.InteropServices.Marshal.ReleaseComObject, in the code above, calling the "GC. Collect (); " First, call "System.Runtime.InteropServices.Marshal.ReleaseComObject ((object) oexcel);" and subtract the reference count by one so that the reference count becomes 0, and when garbage collection occurs, oexcel the corresponding COM object, it was swept out.