Friday, July 22, 2005

Releasing of unmanaged code (COM) from managed code (.NET) calls

While most of the complicated components are still implemented in unmanged code (it will take some long time for us to have a entire managed environment though), we uses Runtime Callable Wrapper (RCW) to wrap up COM objects to be callable from managed code.

However, these has to be used carefully, as the garbage collection won't automatically clear and release the memory used by the COM objects. This problem arise when my colleague asking me about how to solve it, as she observed that there's many EXCEL.EXE running in the taskbar after she run her program which creates excel spreadsheet. While I've read about it, but have never get a chance to use it, thanks again to Dr.Google which always faithfully give me the answers within seconds.

Releasing of unmanaged code (COM) from managed code (.NET) calls:
http://support.microsoft.com/default.aspx?scid=kb;en-us;317109

Below are quoted from the site for easy reference:

To make sure that the Office application quits, make sure that your automation code meets the following criteria:
• Declare each object as a new variable. For example, change the following line of code

oBook = oExcel.Workbooks.Add()


to the following:

dim oBooks as Excel.Workbooks
oBooks = oExcel.Workbooks
oBook = oBooks.Add()


• Use System.Runtime.InteropServices.Marshal.ReleaseComObject when you have finished using an object. This decrements the reference count of the RCW.
• To release the reference to the variable, set the variable equal to Nothing or Null.
• Use the Quit method of the Office application object to tell the server to shut down.

No comments: