简体   繁体   English

为什么线程在获取二维数组值后停止?

[英]Why does the thread stop after getting 2d array value?

I am very new to threading in C# and I can't figure out why my thread is stopping in the middle of the execution. 我对使用C#线程非常陌生,无法弄清楚为什么我的线程在执行过程中停止。

I have build my own terrain solution in Unity3d. 我已经在Unity3d中构建了自己的地形解决方案。 The terrain is composed of chunks. 地形由大块组成。 Each chunk's mesh should be updated on a thread so there aren't any significant frame drops during play. 每个块的网格都应该在线程上更新,以便在播放过程中不会有任何明显的帧丢失。

I create a thread that calls UpdateChunkMeshData with some parameters. 我创建了一个使用某些参数调用UpdateChunkMeshData的线程。 Any time I try to access my 2d array of chunks in the Thread it stops. 每当我尝试访问线程中的二维块数组时,它都会停止。 Why would this happen? 为什么会这样?

Shorted version of the code: 代码的简化版:

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");
}

Arrays are not Thread-Safe. 数组不是线程安全的。 For more information: array and safe access by threads . 有关更多信息: 数组和线程安全访问

If you have some locking in your Chunk you might be facing a deadlock. 如果块中有一些锁定,则可能会遇到死锁。

Why do you use so many threads? 为什么要使用这么多线程? I guess it might be better to create one thread and update all your chunks in one thread. 我想最好创建一个线程并在一个线程中更新所有块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM