I have a class with a field of Dictionary<object, IntPtr>.
I allocate the memory dynamically, when user calls some method of my class:
IntPtr somePointer = Marshal.AllocHGlobal(/*some desired size*/);
Then I’m going to use that memory in another thread. Actually, after doing some job that thread frees allocated memory thru Marshal.FreeHGlobal and removes the appropriate key from collection. But there is some probability for this thread to crash, so I’m thinking about proper finalization.
How I can finalize that entire collection (in case when some thread has crashed and my memory still remains allocated)?
My inclination is to change IntPtr to SafeHandle. Will this help?
Writing a wrapper for the IntPtr could certainly work. But it is unnecessary if the memory should stay valid as long as the item is stored in the dictionary. If that’s the case, it is much easier on the client code if you create your own directory, one that automatically frees the memory when an item is removed from the dictionary. No need for the client to call Dispose() for each item, that’s always an advantage.
To do this, derive your own class from
IDictionary<object, IntPtr>and IDisposable. You can simply delegate most of the method calls to a private dictionary. You’ll want a custom Add() to allocate the memory, Delete to release it. And implement Dispose() and the finalizer to clean up. The code is kinda ugly though:AllocCoTaskMem is the better allocator btw, it doesn’t have the legacy baggage.