gpt4 book ai didi

c# - C#XNA多线程SpriteBatch.End() “Object reference not set to an instance of an object”

转载 作者:行者123 更新时间:2023-12-03 13:20:57 24 4
gpt4 key购买 nike

我是多线程技术的新手,所以暂时搁置了所有其他问题。我在解决如何解决由更快的线程和导致“对象引用未设置为对象实例”的下一个线程而结束的sprite批处理时遇到了麻烦。

哦,如果您发现我的代码有任何其他问题,请随时让我感觉自己像个白痴^^

spriteBatch.Begin();

// Draw Particles
List<Thread> threads = new List<Thread>();
for (int i = 0; i < CPUCores; i++)
{
int tempi = i; // This fixes the issue with i being shared
Thread thread = new Thread(() => DrawParticles(tempi + 1, CPUCores));
threads.Add(thread);
thread.Start();
}
foreach (var thread in threads)
{
thread.Join();
}

// ..More Drawing Code..

spriteBatch.End(); // <-- This is where the program crashes

PS谁认为使用4个空格来表示代码而不是[code] [/code]是个好主意? ¬_¬

最佳答案

您的问题来自SpriteBatch不是线程安全的事实。通过从多个线程写入一个sprite-batch,您正在破坏它。
SpriteBatch(在Immediate模式下除外)的工作方式类似于sprite的List(您不会从多个线程中访问其中之一)还是sprite的缓冲区。因此,可能的解决方案是为每个线程使用一个SpriteBatch。通过在该线程内调用Draw来填充每个Sprite批处理“缓冲区”。

然后,因为您只能在主线程上绘制内容(即:您只能在主线程上调用GraphicsDevice.Draw*,这是SpriteBatch.End内部调用的内容),所以请等待您的工作线程完成每个批次的填充,然后在每个线程上调用End它们来自主线程。这会将子画面绘制到屏幕上。

当然,如果要绘制大量粒子,更好的技术可能是将所有内容卸载到GPU。 Here is an answer为您提供了大概的指导。

关于c# - C#XNA多线程SpriteBatch.End() “Object reference not set to an instance of an object”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12653637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com