473,756 Members | 2,703 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Newbie Question: COM automation / Marshal.Release ComObject / RCW /garbage collector

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

So the question is/are:
Do I need to release each COM object explicit by a call to
Marshal.Release ComObject, 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.Release ComObject 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.Release ComObject
=============== ===========

Excel.Applicati onClass excelApp = null;
Excel.Workbooks workbooks = null;
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
try
{
excelApp = new Excel.Applicati onClass();
excelApp.Displa yAlerts = false;
excelApp.Enable Events = false;

// enumerate all available worsheets
workbooks = excelApp.Workbo oks;
wb = workbooks.Open( path, 0, true, 5, "", "", true,
Excel.XlPlatfor m.xlWindows,
"", false, false, 0, false, false,
Excel.XlCorrupt Load.xlNormalLo ad);
foreach (ws in wb.Sheets)
{
Console.WriteLi ne("Sheet: {0}\n", ws.Name);
Marshal.Release ComObject(ws); // don't even know if thats allowed
here within the iterator loop
}
}
finally
{
if (ws != null) Marshal.Release ComObject(ws);
if (wb != null) Marshal.Release ComObject(wb);
if (workbooks != null) Marshal.Release ComObject(workb ooks);
if (excelApp != null)
{
excelApp.Quit() ;
Marshal.Release ComObject(excel App);
}
}


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.Release ComObject(_obj) ;
_obj = value;
}
}
protected virtual void Dispose(bool disposing)
{
// clean up unmanaged resources
if (_obj != null) Marshal.Release ComObject(_obj) ;
}
void IDisposable.Dis pose()
{
Dispose(true);
GC.SuppressFina lize(this);
}
}

using (ComObj<Excel.A pplicationClass excelApp = new
ComObj<Excel.Ap plicationClass> (new Excel.Applicati onClass()))
{
excelApp.Obj.Di splayAlerts = false;
excelApp.Obj.En ableEvents = false;

// enumerate all available worsheets
using (ComObj<Excel.W orkbooksworkboo ks = new
ComObj<Excel.Wo rkbooks>(excelA pp.Obj.Workbook s))
using (ComObj<Excel.W orkbookwb = new
ComObj<Excel.Wo rkbook>(workboo ks.Obj.Open(pat h, 0, true, 5, "", "",
true, Excel.XlPlatfor m.xlWindows, "", false, false, 0,
false, false,
Excel.XlCorrupt Load.xlNormalLo ad)))
foreach (Excel.Workshee t x in wb.Sheets)
using (ComObj<Excel.W orksheetws = new
ComObj<Excel.Wo rksheet>(x))
Console.WriteLi ne("Sheet: {0}\n", ws.Obj.Name);
excelApp.Obj.Qu it();
}


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

Excel.Applicati onClass excelApp = new Excel.Applicati onClass();
excelApp.Displa yAlerts = false;
excelApp.Enable Events = false;

// enumerate all available worsheets
Excel.Workbook wb = excelApp.Workbo oks.Open(path, 0, true, 5, "", "",
true, Excel.XlPlatfor m.xlWindows,
"", false, false, 0, false, false,
Excel.XlCorrupt Load.xlNormalLo ad);
foreach (Excel.Workshee t ws in wb.Sheets)
Console.WriteLi ne("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.dd d) 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 2734

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

Similar topics

5
5879
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 = "doc123";//aDoc.Name; aDoc.MailMerge.CreateDataSource(ref oFileName, ref missing, ref missing, ref
11
2248
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 returns to the Web form to display. All is OK, except EXCEL remains in the process list in task manager. I am following all guideline in releasing the com components.
5
3036
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 the below API: TargetWorkbook.Save TargetWorkbook.Close
12
3225
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 left running until my application closes. I have tried setting my Excel.Application object to Nothing. I have tried to then fore the GC into action using:
0
945
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 vSQLText, vThreadName As String Try vThreadName = Thread.CurrentThread.Name cFunctions.WriteEventLog("starting report on thread: " &
5
2515
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: System.Runtime.InteropServices.Marshal.ReleaseComObject(Obj);
6
2070
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 wb.Close(false, false, 0); xls.Quit();
5
1509
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 system.process even after the user closes the excel file generated. Here is the code block I'm using Dim oExcelApp As Excel.Application
7
2165
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. The following code (Test1) demonstrates the essence of what I am doing. When I check the processes while ruinning the method, I notice that the Excel process remains after exiting the sub (and until I exit the application) Sub Test1 Dim...
0
9255
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10014
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9844
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9689
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8688
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5289
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3780
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3326
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2647
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.