C#/ MonoGame-卸载游戏关卡时销毁内存中的大对象

问题描述 投票:1回答:1

我正在使用C#/ MonoGame开发游戏,并且想知道如何解决与内存中大型游戏对象有关的垃圾回收问题。

[每次加载新游戏时,我都会创建并存储一个World对象,该对象本身具有一个私有字段,其中包含我的LOD地形系统的四叉树。四叉树递归地包含所有可能的子节点的顶点信息,直到我确定我想要的最小级别。这意味着每个新的World都需要花费约10秒的时间来创建(在后台线程上完成),并且RAM大小约为150MB。

我想确定的是,每次加载新游戏时,都会丢弃旧的World,但据我目前所知,这从来没有发生过。我只是连续六次按“加载游戏”进行了测试,并且游戏所使用的内存达到了1GB,却从未下降过。]

我知道这可能意味着我仍在引用旧的World对象,但是我看不到这是怎么回事。我的主游戏应用程序只有一个私有World,每次我按“加载游戏”时,都会在后台加载器线程上重新创建一个新对象作为新对象:

// This belongs to the game and is referenced when I want to interact with and draw the current World
private World _world;
.
.
// Executes on background loader thread when I press 'load game'
LoadGame()
{
    // This is where the old World is replaced with the new one, so I want the old one to be disposed as it contains ~150MB of useless data
    _world = new World(worldParameters);
}
.
.
Draw()
{
    // Rendering the active World in our draw loop
    DrawWorld(_world);
}

[我尝试将_world设置为null,并强制GC在LoadGame()方法的顶部进行收集,但没有执行任何操作。

有没有一种方法可以强制释放旧对象的内存,或者只是看看我是否在游戏其余部分中无意中指向了它的任何字段,导致它保持活动状态?

我正在使用C#/ MonoGame开发游戏,我想知道如何解决与内存中大型游戏对象有关的垃圾回收问题。每次加载新游戏时,我都会创建并存储一个世界...

c# object memory-management garbage-collection monogame
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.