我有一个加载gameobjects的函数(特别是它在纹理上生成缓存,以便以后使用它)
// This function is called during the game loading screen (with progress bar)
public void Loader()
{
for (int i = 0; i < game_objects_.Count; ++i) // ~250
{
game_objects_[i] = new GameObject();
game_objects_[i].DrawCache(spriteBatch);
}
GC.Collect();
}
// Inside GameObject class
...
public GameObject()
{
// ...
// GameObject is composed of 3 (different) objects, to be drawn in one texture.
piece1_ = new Piece1();
piece2_ = new Piece2();
piece3_ = new Piece3();
}
public void DrawCache(spriteBatch s)
{
// On RenderTarget2D cache_
piece1_.Draw(s);
piece2_.Draw(s);
piece3_.Draw(s);
// Due to the fact that I won't use anymore these 3 objects, but just the Whole "cache_"
// I can "destroy" them
piece1_.Dispose();
piece2_.Dispose();
piece3_.Dispose();
}
我做得对吗?我问这个是因为在加载屏幕之后(在Loader功能结束时),我仍然在游戏中得到一些“小随机冻结”约2秒钟,所以我想也许GC正在做一些事情虽然功能有完成,或者我对Dispose()的使用方式有不妥的承诺。
答案 0 :(得分:0)
GC.Collect();
,除非你确定自己在做什么:C#不是C ++,你不能控制对象的生命周期,特别是你不能控制释放内存的时刻。调用GC.Collect()通常会产生更多问题,并且不会修复任何问题。 除非您的程序消耗了几乎所有可用内存(您应该检查内存量,否则GC没有理由让您的应用程序冻结。
注意:
GameObject
内,您应该将一些内容放入一个列表中并对其进行迭代:代码将更易于维护和阅读。using
声明,以自动(和强制)调用Dispose()示例:
public interface IPiece : IDisposable
{
void Draw(spriteBatch s);
}
// ...
public void DrawCache(spriteBatch s)
{
// On RenderTarget2D cache_
foreach(var piece in this.pieces)
{
using(piece)
{
piece_.Draw(s);
}
}
}