CsWinRT icon indicating copy to clipboard operation
CsWinRT copied to clipboard

Report native memory pressure to GC

Open manodasanW opened this issue 1 year ago • 0 comments

This PR reports the native memory pressure of any CsWinRT projected RCWs to the .NET GC. The .NET GC keeps track of managed memory and is not aware of native memory usage of anything that the C# managed objects are holding onto. So, in the case of CsWinRT projected RCWs, the .NET GC is aware of the managed memory usage of CsWinRT's RCW projection implementation, but the native WinRT object being held on can be using much more memory that the GC isn't aware of. By reporting this native memory pressure to the .NET GC, .NET is able to run the GC more often as needed based on memory usage and thereby making sure any collected objects are indeed finalized releasing the native memory. There is another similar change on the WinUI side this works together with which reports WinUI native memory pressure.

  • Reports native memory pressure based on the GCPressure attribute on RCWs and how much it indicates to report
  • Reports basic native memory pressure for all IObjectReferences as they are holding onto WinRT objects. This PR uses a simplified approach to achieving this by reporting it for any IObjectReference. In theory, multiple IObjectReferences can be pointing to the same WinRT object and we don't need to report native memory pressure each time, but we shouldn't have too much of an impact by doing so. In order to do the non-simplified approach, it will require another object allocation which isn't finalized until all the IObjectReferences held onto by an RCW or was from a QI from it is disposed. This gets more complicated to implement due to needing to wait for all related IObjectRefrences to finalize so deferring on that until there is a need for it.
  • Make use of the ComWrapper APIs that were added after .NET 5

manodasanW avatar Feb 22 '24 22:02 manodasanW