473,395 Members | 1,458 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Newbie Question: COM automation / Marshal.ReleaseComObject / RCW /garbage collector

Hello there,
I have some doubts about the best practice for using COM automation,
the Runtime
Callable Wrapper (RCW) and Marshal.ReleaseComObject.

So the question is/are:
Do I need to release each COM object explicit by a call to
Marshal.ReleaseComObject, does the RCW take care of that or does it
leaks
unmanaged resources?

If I understand the docs correctly without the explicit call to
Marshal.ReleaseComObject the RCW objects release the COM objects in
their
finalizer. But as I read several times in this NG, it's a bad thing to
depend
on the finalizer to release unmanaged resources because the garbage
collector
runs non-deterministic so someone never knows when.
Unfortunately the RCW objects don't implement the dispose pattern so
someone
could dispose the underlying COM object deterministic. And even then,
the
codingstyle is a mess (as you'll see in my examples later).

So what is the best (or common) practice for COM automation:

Example 1: Explicit calls of Marshal.ReleaseComObject
==========================

Excel.ApplicationClass excelApp = null;
Excel.Workbooks workbooks = null;
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
try
{
excelApp = new Excel.ApplicationClass();
excelApp.DisplayAlerts = false;
excelApp.EnableEvents = false;

// enumerate all available worsheets
workbooks = excelApp.Workbooks;
wb = workbooks.Open(path, 0, true, 5, "", "", true,
Excel.XlPlatform.xlWindows,
"", false, false, 0, false, false,
Excel.XlCorruptLoad.xlNormalLoad);
foreach (ws in wb.Sheets)
{
Console.WriteLine("Sheet: {0}\n", ws.Name);
Marshal.ReleaseComObject(ws); // don't even know if thats allowed
here within the iterator loop
}
}
finally
{
if (ws != null) Marshal.ReleaseComObject(ws);
if (wb != null) Marshal.ReleaseComObject(wb);
if (workbooks != null) Marshal.ReleaseComObject(workbooks);
if (excelApp != null)
{
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
}
}


Example 2: Using a wrapper to implement dispose pattern
========================

public class ComObj<T: IDisposable where T : class
{
private T _obj;
public ComObj() { _obj = null; }
public ComObj(T x) { _obj = x; }
~ComObj() { Dispose(false); }
public T Obj {
get { return _obj; }
set {
if (_obj != null) Marshal.ReleaseComObject(_obj);
_obj = value;
}
}
protected virtual void Dispose(bool disposing)
{
// clean up unmanaged resources
if (_obj != null) Marshal.ReleaseComObject(_obj);
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}

using (ComObj<Excel.ApplicationClassexcelApp = new
ComObj<Excel.ApplicationClass>(new Excel.ApplicationClass()))
{
excelApp.Obj.DisplayAlerts = false;
excelApp.Obj.EnableEvents = false;

// enumerate all available worsheets
using (ComObj<Excel.Workbooksworkbooks = new
ComObj<Excel.Workbooks>(excelApp.Obj.Workbooks))
using (ComObj<Excel.Workbookwb = new
ComObj<Excel.Workbook>(workbooks.Obj.Open(path, 0, true, 5, "", "",
true, Excel.XlPlatform.xlWindows, "", false, false, 0,
false, false,
Excel.XlCorruptLoad.xlNormalLoad)))
foreach (Excel.Worksheet x in wb.Sheets)
using (ComObj<Excel.Worksheetws = new
ComObj<Excel.Worksheet>(x))
Console.WriteLine("Sheet: {0}\n", ws.Obj.Name);
excelApp.Obj.Quit();
}


Example 3: Let the finalizer of RCW free the COM objects
=======================

Excel.ApplicationClass excelApp = new Excel.ApplicationClass();
excelApp.DisplayAlerts = false;
excelApp.EnableEvents = false;

// enumerate all available worsheets
Excel.Workbook wb = excelApp.Workbooks.Open(path, 0, true, 5, "", "",
true, Excel.XlPlatform.xlWindows,
"", false, false, 0, false, false,
Excel.XlCorruptLoad.xlNormalLoad);
foreach (Excel.Worksheet ws in wb.Sheets)
Console.WriteLine("Sheet: {0}\n", ws.Name);

excelApp.Quit();

Example 3 is the most short and readable code but I'm not sure if I
should depend on the finalizer to
clean up the unmanaged (COM) resources.

Example 1 and 2 seems the most relieable mechanism but had some big
disadvantages:
- each COM object has to be wrapped in a variable (Ex1) or wrapper
object (Ex2)
- the foreach loop is a pain in the butt
- unused return values (COM objects) had to be freed explicitly
- property chaining (aaa.bbb.ccc.ddd) is not possible, otherwise the
intermediate objects would not be released.
So what is the best/usual practice to implement COM automation?
Regards,
Martin
Sep 29 '08 #1
0 2707

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Picho | last post by:
Hi all, I have a problem automating word (office xp). I am trying to create a mailmerge datasource using this code: object oFieldsVector = (object)fieldsVector; object oFileName =...
11
by: Tim Marsden | last post by:
Hi, I have a routine which is call from a ASP.NET web form. This routine creates an excel application, opens a workbook , runs some code to update the workbook, saves it as HTML on the sever and...
5
by: Wenke Ji | last post by:
Hi I open a Excel workbook using below API: Set ExcelServer = CreateObject("EXCEL.Application") Set TargetWorkbook = ExcelServer.Workbooks.Open (CurrentBook) Befor the programm exit , I use...
12
by: elziko | last post by:
I'm using late binding (I must) to automate Excel. My code opens Excel after createing and poulating some sheets. My problem is that when the user finally decides to close Excel its process is...
0
by: Steven Thomas | last post by:
I have a windows service that uses office xp automation. Here is the code --------------------------------------- Public Sub CAccessSnapShot() Try Dim objAccess As New Access.Application() Dim...
5
by: Michael Moreno | last post by:
Hello, In a class I have this code: public object Obj; If Obj is a COM object I would like to call in the Dispose() method the following code: ...
6
by: Gunawan | last post by:
Dear All, I have create an excel (COM Object) using this code Excel.Application xls = new Excel.Application(); but I can not remove it from memory although I have using close and quit ...
5
by: Satish Itty | last post by:
Hi all, I using excel automation to generate some reports in excel. I guess I'm not doing it correctly because Every time the report is run it leaves a Excel.exe process open in the...
7
by: =?Utf-8?B?VGVycnkgSG9sbGFuZA==?= | last post by:
I have a vb.net app that opens an excel worksheet, reads data and then closes the sheet. Im noticing that the Excel process is still running after I have closed and disposed of my excel objects. ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.