我正在使用本地服务器/客户端设置来测试我编写的点渲染程序。客户端可以正确地从服务器接收数据点,但是由于需要处理大量数据点,我使用了System.Threading.Tasks
库来利用多线程来更快地处理数据。
The output of the program should look like this (which currently takes an hour to process):
However, when using my multithreaded solution, it comes out like this:
我用来设置多线程的代码在下面(初始化过程已在示例上方进行了处理)。
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);
}
}
我假设多线程正在以某种方式破坏数据。我需要更改或修复以获得正确的结果吗?
答案 0 :(得分:-1)
我实现了一个try-catch循环,发现单行损坏的数据是问题的根源。这似乎是由于该程序的服务器插槽部分所致,因此在这里我将不对其进行进一步讨论,但是try-catch循环是找到问题所在并允许程序继续运行的绝佳解决方案。尽管发生错误。