Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of using GC.AddMemoryPressure with an unmanaged resource?

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?

like image 301
devoured elysium Avatar asked Jul 19 '09 03:07

devoured elysium


People also ask

What are unmanaged resources?

The most common types of unmanaged resources are objects that wrap operating system resources, such as files, windows, network connections, or database connections.

Why we use GC collect?

It performs a blocking garbage collection of all generations. All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.


1 Answers

It is provided so that the GC knows the true cost of the object during collection. If the object is actually bigger than the managed size reflects, it may be a candidate for quick(er) collection.

Brad Abrams entry about it is pretty clear:

Consider a class that has a very small managed instance size but holds a pointer to a very large chunk of unmanaged memory. Even after no one is referencing the managed instance it could stay alive for a while because the GC sees only the managed instance size it does not think it is “worth it” to free the instance. So we need to “teach” the GC about the true cost of this instance so that it will accurately know when to kick of a collection to free up more memory in the process.

like image 155
Steven Lyons Avatar answered Sep 20 '22 17:09

Steven Lyons