Is it possible to intercept (or be aware of) COM Reference counting on CLR objects exposed to COM

前端 未结 10 1065
礼貌的吻别
礼貌的吻别 2020-12-08 02:56

I have rephrased this question.

When .net objects are exposed to COM Clients through COM iterop, a CCW (COM Callable Wrapper) is created, this sits between

10条回答
  •  伪装坚强ぢ
    2020-12-08 03:54

    To my knowledge, the GC already provides support for what you are trying to do. It is called Finalization. In a purely managed world, best practice is to avoid Finalization, as it has some side effects that can negatively impact the performance and operation of the GC. The IDisposable interface provides a clean, managed way of bypassing object finalization and providing cleanup of both managed and unmanaged resources from within managed code.

    In your case, you need to initiate cleanup of a managed resource once all unmanaged references have been released. Finalization should excel at solving your problem here. The GC will finalize an object, always, if a finalizer is present, regardless of how the last references to a finalizable object were released. If you implement a finalizer on your .NET type (just implement a destructor), then the GC will place it in the finalization queue. Once the GC collection cycle is complete, it will process the finalization queue. Any cleanup work you perform in your destructor will occur once the finalization queue is processed.

    It should be noted that if your finalizable .NET type contains references to other .NET objects which in turn require finalization, you could invoke a lengthy GC collection, or some of the objects may survive for longer than they would without finalization (which would mean they survive a collection and reach the next generation, which is collected less frequently.) However, if the cleanup work of your .NET objects that use CCW's is not time sensitive in any fashion, and memory usage is not a huge issue, some extra lifetime shouldn't matter. It should be noted that finalizable objects should be created with care, and minimizing or eliminating any class instance level references to other objects can improve your overall memory management via the GC.

    You can read more about finalization in this article: http://msdn.microsoft.com/en-us/magazine/bb985010.aspx. While it is a rather old article from back when .NET 1.0 was first released, the fundamental architecture of the GC is unchanged as of yet (the first significant changes to the GC will be arriving with .NET 4.0, however they are related more to concurrent GC execution without freezing the application threads than changes to its fundamental operation.)

提交回复
热议问题