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

后端 未结 4 400
忘掉有多难
忘掉有多难 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:33

    Put it this way, still assuming the 8 byte managed objects each referring to a 2 MB unmanaged image. The GC might wait a long time before collecting hundreds or thousands of the little managed objects, because they are so small. That would mean that also hundreds or thousands of linked 2 MB unmanaged chunks will stay alive, awaiting removal. That could become a huge problem. By adding 2 MB of memory pressure in the constructor you will make GC think that the managed object is not 8 bytes big but rather 8 bytes + 2 MB. That will trigger collection way earlier.

    Don't forget the Remove call.

    Of course if you dispose yourself then you won't need all that.

提交回复
热议问题