As we all know, in the .net world, programmers are only responsible for creating objects using new, and the destruction of objects is completely left to the garbage collector. Only when garbage collection occurs, types in .net will be destroyed. This usually causes nothing wrong. However, special problems arise when using unmanaged COM objects.
COM uses reference counting to determine the lifetime of the object. Every time the COM client references the object, it calls
IUnKnown->AddRef(), and every time the object is released, it is called
IUnKnown->Release(), releases the instance once the reference count reaches zero.
The problem arises, let's look at the following code:
This is a c# code that uses the excel com component to export excel files to the client that is widely circulated in the asp.net version of CSDN. Before adding this code, the wizard for adding com references was run.
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 storage address
oExcel.ActiveWorkbook.SaveCopyAs (mm);
oExcel.Quit();
//GC.Collect();
Response.Redirect(filename+".xls");
This code can realize the function of exporting files, but if you look at the Windows Task Manager, you will find the wonderful scene as shown below
So, someone added "GC.Collect();" to the code. Very good, there are not so many EXCEL.EXEs, as shown below.
But how can we achieve complete release?
Fortunately, in .net, programmers are allowed to explicitly call the Release method of com themselves. This method is packaged by .net and is called System.Runtime.InteropServices.Marshal.ReleaseComObject. In the above code,
Before calling "GC.Collect();", first call "System.Runtime.InteropServices.Marshal.ReleaseComObject((object)oExcel);"
Decrement the reference count by one, so that the reference count becomes zero. When garbage collection occurs, the COM object corresponding to oExcel will be swept away.