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

后端 未结 4 375
忘掉有多难
忘掉有多难 2021-01-01 18:41

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 poi

4条回答
  •  礼貌的吻别
    2021-01-01 19:30

    These methods allow the runtime to have some sense of how much unmanaged memory is being allocated by the process. Without calling these functions, it may not be able to see the true amount of unmanaged memory in use within the process.

    However I disagree with the other answers here regarding an association between the memory being referred to and a particular GC object.

    Consider:

    var buffer = IntPtr.Zero;
    try
    {
        buffer = Marshal.AllocHGlobal(size);
        GC.AddMemoryPressure(size);
    
        // ... use buffer ...
    }
    finally
    {
        Marshal.FreeHGlobal(buffer);
        GC.RemoveMemoryPressure(size);
    }
    

    There is no way for the GC to assign the size to a specific object. This code could even exist in a static method.

    Therefore I assert that the statement 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 is incorrect and misleading.

    Instead this method might cause the GC to collect earlier than it would otherwise, in an effort to avoid running out of memory.

提交回复
热议问题