如何强制垃圾收集器移动内存中的对象 [英] how to force garbage collector to move an object in memory

查看:66
本文介绍了如何强制垃圾收集器移动内存中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了测试与非托管代码交互的某些方案,我需要强制GC将对象移动到内存中.

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

我有以下代码来测试对象的运动.在以某种方式迫使gc移动mc 部分中应该写什么代码,以便将两个不同的地址打印到控制台上?

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

推荐答案

我遇到了类似的问题",并且想出了一个解决方案".我知道这段代码很奇怪,绝不应该投入生产,但是当您要确保互操作代码正确处理内存重新分配时,它足以进行测试.

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

这篇关于如何强制垃圾收集器移动内存中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆