Reputation: 965
I'm creating a Memory holder class that wraps around a heap object, and I want to determine the dispose of the object is very force for GC.
I want something like:
myObj = null; //Immediately call to ~myObj()
Upvotes: 0
Views: 69
Reputation: 81159
COM objects expect to be notified promptly when they go out of scope, but .NET does not support prompt notification except via Dispose
. You should call IUnknown.Release
in your dispose method but you must ensure before calling IUnknown.Release
that there is no way that anyone might ever try to use that COM object again. Attempting to use a COM object that has after Release
, or even simply trying to call Release
upon it again, is a recipe for disaster.
I would suggest, therefore, that no reference to the COM object itself ever be released to outside code. Instead, have the class which holds the object forward all requests to the object itself within a lock (to ensure that code doesn't attempt simultaneous accesses), and have your Dispose
method acquire the lock, call Release
on the object, and then invalidate the reference. Any future attempts to manipulate the object which aren't otherwise trapped will cause a NullReferenceException
which isn't brilliant, but is still way better than trying to use a COM
object after it is released.
Upvotes: 0
Reputation: 99869
The .NET framework and runtime provides two features for applications which use unmanaged resources.
IDisposable
interface allows code to release resources at a specific time, by explicitly or implicitly calling the Dispose()
method. (The using
statement in C# provides implicit support for this call.)Dispose()
method, a finalizer can be used to prevent long-running applications from leaking these resources over time. User code generally should not include user-defined finalizers; instead, create (or use an existing) class which extends SafeHandle
and implement the ReleaseHandle
method to define the release behavior.Note that IDisposable.Dispose()
is the only supported mechanism for deterministic resource cleanup. Eventual cleanup is a non-deterministic fallback that should be avoided.
Upvotes: 2
Reputation: 56536
No, you can't do this. You should simply use IDisposable
as it's meant to be used.
Upvotes: 2