首页 > 解决方案 > 我的数据是否由于多线程而损坏?

问题描述

我正在使用本地服务器/客户端设置来测试我编写的点渲染程序。客户端正确地从服务器接收数据点,但是由于需要处理大量的数据点,我使用该System.Threading.Tasks库来采用多线程来更快地处理数据。

程序的输出应该如下所示(目前需要一个小时来处理):

但是,当使用我的多线程解决方案时,结果如下:

我用来设置多线程的代码如下(初始化,在示例上方进行了处理)。

void Update () {
    //Read bytes data from server stream
    length = stream.Read(bytes, 0, bytes.Length);
    if(length != 0){    

        // Convert byte array to string message
        startedStreaming = true;
        finishedStreaming = false;
        serverMessage += Encoding.UTF8.GetString(bytes); 
    }

    else{
        finishedStreaming = true;
    }

    if(startedStreaming == true && finishedStreaming == true){
        startedStreaming = false;
        rendered = false;
        readyToProcess = false;
        StartCoroutine(DataStreaming());
    }
    if(readyToRender == true && rendered == false){
        rendered = true;
        Debug.Log("Rendering");
        pcloud.updateBuffer();
    }
}



private IEnumerator DataStreaming(){   

    //Convert bytes data to readable strings once finished receiving
    if(finishedStreaming == true && readyToProcess == false){

        if(renderer.enabled == false){
            renderer.enabled = true;
        }

        newVectors = serverMessage.Split(new char[]{'\n'} );

        Debug.Log("Message split");

        pcloud._pointData =  new PointCloudData.Point[newVectors.Length];

        readyToProcess = true;
    }

    //Convert strings into numerical values and render once finished
    if(readyToProcess == true && readyToRender == false){
        readyToRender = true;
        Debug.Log("rendering, "+ Time.realtimeSinceStartup);
        Parallel.For(0, newVectors.Length, (coord) =>{
            row = newVectors[coord].Split(new char[]{','});
            float x = int.Parse(row[0]);
            float y = int.Parse(row[1]);
            float z = int.Parse(row[2]);

            pcloud._pointData[coord].position = new Vector3((float)(x/pixelsPerUnit), (float)(y/1000f), (float)(z/pixelsPerUnit));

            pcloud._pointData[coord].color = Pcx.PointCloudData.EncodeColor(dict[(int)y]); 
        });
    }

    if(readyToRender ==  true){
        yield return new WaitForSeconds(10);
    }
}

我假设多线程以某种方式破坏了数据。我需要更改或修复什么以获得正确的结果吗?

标签: c#multithreadingunity3dstreamingrendering

解决方案


我已经实现了一个 try-catch 循环,并发现一行损坏的数据是问题的根源。这似乎是由于程序的服务器套接字部分,所以我不会在这里进一步讨论,但是 try-catch 循环是一个很好的解决方案,可以找到问题发生的位置,并允许程序继续尽管发生错误。


推荐阅读