Tie destruction of an object (sealed) to destruction of an unmanaged buffer
I'll explain my situation first: I'm interested of using the Bitmap constructor that takes scan0, stride and format, because I'm decoding tiled images and I'd like to choose my own stride so I can decode the tiles without caring about the bounds in the decoder part.
Anyway, the problem is that the documentation says:
The caller is responsible for allocating and freeing the block of memory specified by the scan0 parameter. However, the memory should not be released until the related Bitmap is released.
I can't release the buffer easily, because the Bitmap is then passed 开发者_如何转开发to another class that will eventually destroy it and I don't have control over it. Is there some way (hacky, I know) to tell the GC to also release my buffer when the Bitmap is destroyed?
(Also, any alternative solution is welcome).
Have a look at the ConditionalWeakTable<TKey, TValue> Class. It's a special dictionary class where the keys are weakly referenced, and the values are kept alive as long as the key is alive.
You could instantiate a ConditionalWeakTable<Bitmap, UnmanagedMemoryHandle> where UnmanagedMemoryHandle is a custom class that contains the pointer to the unmanaged memory and releases that memory when it's disposed or finalised. The Bitmap would be weakly referenced by the table; UnmanagedMemoryHandle will be kept alive as long as the Bitmap lives, so the unmanaged memory will be freed when the Bitmap is garbage collected.
If a class creates an unmanaged resource, then don't let anyone else destroy it, because it will be messy. Only use the unmanaged resource inside the class that creates it. You can clone the bitmap and publish that, for example.
No, you are lost here. Problem is that you are back in the C++ times if keeping track of memory, and basically you "loose" the memory responsibility. No way to realize when the memoery is freed.
精彩评论