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();
}
}