My C# program uses a COM component that has a ton of various interfaces and subobjects. The problem is each time I retrieve some COM interface an RCW is created and that RCW exists for unknown time (until collected by GC). Each RCW holds some object in the COM server.
The COM component is an out-proc server, so its objects reside in a separate quite heavy-weight process that won't terminate until all objects residing in it are released. I want all object to be releases ASAP so that I know for sure that once I released the last object the out-proc server process terminates and no longer consumes system resources. That's not my paranoia - having several heavyweight processes consuming system resources, especially memory, is really bad for performance.
So far I crafted a generic class that implements IDisposable
, accepts a reference to the object (RCW in fact) and calls Marshal.FinalReleaseComObject
in Dispose
implementation.
For the sake of this question let's temporarily ignore possible problems arising from using FinalReleaseComObject()
- I'm aware of them and can tolerate them.
The real problem is I'm forced to either use using
for all objects or to write finally
clauses and call Dispose()
there. It works, but code gets rather cluttered with lots of extra wiring and that bothers me big time.
For example, I need to assign a string to someObject.Params.ColorParams.Hint
property - I can't just write
someObject.Params.ColorParams.Hint = whatever;
because for each accessor there will be a COM object that I need to get released, so I have this instead:
using( MyWrapper<IParams> params = new MyWrapper<IParams>( someObject.Params ) ) {
using( MyWrapper<IColorParams> colorParams =
new MyWrapper<IColorParams>( params.Controlled ) )
{
colorParams.Controlled.Hint = whatever;
}
}
and that's the most trivial example - sometimes I need to access something five levels deep and then I write a set of using
statements five level deep.
Is there a more elegant solution to the problem?