我尝试创建我的小粒子系统。我有带有粒子列表的 ParticleManager 并在画布上绘制我的粒子。我只需在 init() 函数中创建任何新对象,如 Paint 等!如果粒度 < 0,我将其删除:
for (int particle = 0; particle < particles.Count; particle++)
{
particles[particle].Update(); //particle size--;
if (!particles[particle].state) // size > 0 ? true : false
{
particles[particle] = null;
//here I tried all variations like
//((IDisposable)particles[particle]).Dispose();
//GC.SuppressFinalize(particles[particle]);
//System.GC.ReRegisterForFinalize(particles[particle]);
//((Java.Lang.Object)particles[particle]).Dispose(); and etc
particles.Remove(particles[particle]);
}
然后我创建新的粒子并将其添加到我的列表中。我在日志中看到的内容:
GC cleanup summary: 1063 objects tested - resurrecting 1002.
GC cleanup summary: 1053 objects tested - resurrecting 992.
...
GC cleanup summary: 1052 objects tested - resurrecting 988.
46800 outstanding GREFs. Performing a full GC!
然后我的渲染线程中有 10-15(!!!)秒暂停!!!我阅读了官方文档,但没有任何解决方案。我分析并比较了我的代码与单 JetBoy 示例,但 JetBoy 的日志没有关于 GC 的任何内容。虽然我用 JetBoy 的例子写了我的程序。如何解决完整的 GC 问题?
编辑:MainThread.cs
public override void Run()
{
Log.Verbose("Run()", "r");
Canvas c;
while (mRun) {
c = null;
mPassedTime = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
if (mTimerTask == null) {
mTimerTask = new CountDownTimerTask(this);
mTimer.Schedule(mTimerTask, mTaskIntervalInMillis);
}
try {
c = mSurfaceHolder.LockCanvas(null);
lock (mSurfaceHolder)
DoDrawRunning(c);
} finally {
if (c != null)
mSurfaceHolder.UnlockCanvasAndPost(c);
}
}
}
private void DoDrawRunning(Canvas canvas)
{
#region particles
for (int eng = 0; eng < engines.Count; eng++)
{
engines[eng].Update();
engines[eng].Draw(canvas);
}
#endregion
}
粒子工程.cs
public void Update() {
if (particles.Count < maxTotal) {
for (int i = 0; i < total; i++) {
if (addNewB)
particles.Add(GenerateNewParticle()); // return new Particle
}
}
for (int particle = 0; particle < particles.Count; particle++) {
particles[particle].Update(); // position and size update
if (!particles[particle].state) // size > 0 ?
particles.RemoveAt(particle);
}
}
public void Draw(Canvas canvas) {
for (int j = 0; j < 3; j++) // 3 particle color-levels draw
for (int index = 0; index < particles.Count; index++)
particles[index].Draw(canvas, j);
}
粒子.cs
public void Draw(Canvas canvas) {
mPaint.StrokeWidth = mSize;
mPaint.Color = Color.Blue;
canvas.DrawPoint(posX, posY, mPaint);
}