我很新的線程在C#中,我無法弄清楚爲什麼我的線程停在執行中。爲什麼線程在獲取2d數組值後停止?
我在Unity3d中構建了自己的地形解決方案。地形由大塊組成。每個塊的網格應該在線程上更新,因此在播放過程中沒有任何明顯的幀丟失。
我使用一些參數創建了一個調用UpdateChunkMeshData的線程。任何時候我嘗試在線程中訪問我的二維數組塊時,它會停止。爲什麼會發生?
代碼的短路版本:
public Chunk[,] Chunks;
public class Chunk
{
public GameObject gameObject;
public float[,] Heights;
public int Resolution;
public bool NeedsToUpdate;
public bool Busy;
public bool MeshReady;
}
for (int x = 0; x < ChunkCountX; x++)
{
for (int y = 0; y < ChunkCountY; y++)
{
Thread thread = new Thread(() => {
Debug.Log("Starting thread for chunk " + ChunkIndexX + ", " + ChunkIndexY);
UpdateChunkMeshData(x, y, Resolution, false, false, false, false);
Debug.Log("Finished thread for chunk " + ChunkIndexX + ", " + ChunkIndexY);
});
thread.Start();
}
}
private void UpdateChunkMeshData(int ChunkX, int ChunkY, int someOtherParams)
{
Debug.Log("Thread started fine");
// As soon as I try to access any of the chunks in the array the thread stops. I don't get any errors either.
Debug.Log(Chunk[ChunkX, ChunkY].Heights[x, y]);
Debug.Log("Thread doesn't print this");
}
你確定你的'Chunks'數組被正確初始化了嗎?看起來你可能正在訪問一個不存在的數組位置,所以'Thread'終止於一個異常。 – Corey
我確定它已被初始化。 –