how to force garbage collector to move an object in memory

烈酒焚心 提交于 2021-01-28 17:43:52

问题


In order to test some scenarios that interact with unmanaged code, I need to force the GC to move an object in memory.

I have the following code to test object movement. What code should be written in the section somehow force gc to move mc so that two different addresses are printed to the console?

[StructLayout(LayoutKind.Sequential)]
class MyClass
{
    public int i;
}

class Program
{
    static void Main(string[] args)
    {
        MyClass mc = new MyClass();

        // print address of mc
        var handle = GCHandle.Alloc(mc, GCHandleType.Pinned);
        Console.WriteLine(handle.AddrOfPinnedObject());
        handle.Free();

        // somehow force gc to move mc

        // print new address of mc
        handle = GCHandle.Alloc(mc, GCHandleType.Pinned);
        Console.WriteLine(handle.AddrOfPinnedObject());
        handle.Free();
    }
}

回答1:


I had similar "problem" and I came up with a "solution". I am aware that this code is weird and should never be put in production but it is good enough for testing when you want to make sure that your interop code handles memory re-allocations correctly.

var firstData = new int[10000];
var data = new int[50];

GCHandle handle;

handle = GCHandle.Alloc(data, GCHandleType.Pinned);
Console.WriteLine(handle.AddrOfPinnedObject());
handle.Free();

firstData = null;
GC.AddMemoryPressure(10000000);
GC.Collect();
GC.RemoveMemoryPressure(10000000);

handle = GCHandle.Alloc(data, GCHandleType.Pinned);
Console.WriteLine(handle.AddrOfPinnedObject());
handle.Free();


来源:https://stackoverflow.com/questions/30921393/how-to-force-garbage-collector-to-move-an-object-in-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!