Working with COM Exe in C#
Credit goes to Peter A. Bromberg for this one. In his article, he talks about creating dynamic excel workbooks in C# within an ASP.NET page.
What I learnt from the article was how we can properly release a COM object. There are two methods that we are gets the deallocation done. They are :-
1) GC.Collect(); // this one forces garbage collection
2) System.Runtime.InteropServices.Marshal.ReleaseComObject (object); // this one releases the passed in COM object wrapper instance
The pattern the author (Peter A. Bromberg) uses to create and release COM Wrapped Excel objects is :-
1) call GC.Collect() to force collection of existing COM Objects waiting to be released.
2) instantiate the COM Wrapped Excel objects (Workbook, Worksheet etc.)
3) do the thing...
4) call the Close() or Quit() methods on the objects when done.
5) call System.Runtime.InteropServices.Marshal.ReleaseComObject(object) once for each COM object created.
6) set each object variable to null.
7) call GC.Collect() again
8) be relieved and reminisce the cool VB6 way of doing the above (Set obj = Nothing)
Here is a slightly altered & annotated code fragment (in C#) that shows how it is done :-
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
// Step 1
GC.Collect();// clean up any other excel guys hangin' around...
// Step 2
oXL = new Excel.Application();
oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
// Step 3
// this part will actually be filling in the values into the sheet
fillValues(oSheet);
....
// Step 4
// Need all following code to clean up and extingush all references!!!
oWB.Close(null,null,null);
oXL.Workbooks.Close();
oXL.Quit();
// Step 5
System.Runtime.InteropServices.Marshal.ReleaseComObject (oXL);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oWB);
// Step 6
oSheet=null;
oWB=null;
oXL = null;
// Step 7
GC.Collect(); // force final cleanup!
Although I am yet to fully understand what goes on behind the scenes, I have used the above mention pattern, and it works. Excel exposes its functionality through a COM Exe. Maybe, we don't need to do all this for a COM Dll, but that is for later.