I’ve read about this issue on MSDN and on CLR via c#.
Imagine we have a 2Mb unmanaged HBITMAP allocated and a 8 bytes managed bitmap pointing to it. What’s the point of telling the GC about it with AddMemoryPressure if it is never going to be able to make anything about the object, as it is allocated as unmanaged resource, thus, not susceptible to garbage collections?
The point of AddMemoryPressure is to tell the garbage collector that there’s a large amount of memory allocated with that object. If it’s unmanaged, the garbage collector doesn’t know about it; only the managed portion. Since the managed portion is relatively small, the GC may let it pass for garbage collection several times, essentially wasting memory that might need to be freed.
Yes, you still have to manually allocate and deallocate the unmanaged memory. You can’t get away from that. You just use AddMemoryPressure to ensure that the GC knows it’s there.
Edit:
I think I see your issue.
Yes, if you can guarantee that you always call
Dispose, then yes, you don’t need to bother with AddMemoryPressure and RemoveMemoryPressure. There is no equivalence, since the reference still exists and the type would never be collected.That said, you still want to use AddMemoryPressure and RemoveMemoryPressure, for completeness sake. What if, for example, the user of your class forgot to call Dispose? In that case, assuming you implemented the Disposal pattern properly, you’ll end up reclaiming your unmanaged bytes at finalization, i.e. when the managed object is collected. In that case, you want the memory pressure to still be active, so that the object is more likely to be reclaimed.