Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GC.AddMemoryPressure for unmanaged objects

Tags:

c#

.net-4.0

What is the correct way to use Add/RemoveMemoryPressure for unmanaged objects? I have an unmanaged object- but it makes heavy use of, e.g., STL containers. Am I supposed to constantly update the managed GC with every change to the total size of the unmanaged object? Or just it's raw allocation size? And when do I call RemoveMemoryPressure? Finalizer? Dispose()?

like image 739
Puppy Avatar asked Nov 25 '10 23:11

Puppy


1 Answers

From here (and noted by @Wim Coenen):

In the simplest usage pattern, a managed object allocates unmanaged memory in the constructor and releases it in the Dispose or Finalize method. Call the AddMemoryPressure method after allocating the unmanaged memory, and call the RemoveMemoryPressure method after releasing it.

In more complicated scenarios, where the unmanaged memory allocation changes substantially during the lifetime of the managed object, you can call the AddMemoryPressure and RemoveMemoryPressure methods to communicate these incremental changes to the runtime.

So you have to decide how much effort to put into tracking these changes and how much benefit you will get.

like image 190
Mitch Wheat Avatar answered Oct 03 '22 05:10

Mitch Wheat