Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does GC.AddMemoryPressure() know which object to add memory pressure to?

I recently had need to use GC.AddMemoryPressure and it struck me as strange that it doesn't accept the object to add memory pressure to as an argument. I assume because it's so closely tied to the runtime, there is some mechanism by which the this pointer gets passed to the method. My question is threefold:

  1. How does the this pointer get passed to the method?
  2. I notice no exception is thrown when calling it from a static method. What happens in this case?
  3. Why do other GC methods such as GC.SupressFinalize and GC.ReRegisterForFinalize take an object argument where this method doesn't need one?
like image 330
Grokys Avatar asked Jan 25 '12 14:01

Grokys


1 Answers

No, it's not explicitly associated with any specific object. The assumption is that at disposal/finalize time, the same object will remove that pressure. From the docs:

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, the memory pressure may change over time - but it's still expected to be with the co-operation of the object in question.

like image 166
Jon Skeet Avatar answered Nov 09 '22 10:11

Jon Skeet