c# - 我的数据是否由于多线程而损坏?
问题描述
我正在使用本地服务器/客户端设置来测试我编写的点渲染程序。客户端正确地从服务器接收数据点,但是由于需要处理大量的数据点,我使用该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);
}
}
我假设多线程以某种方式破坏了数据。我需要更改或修复什么以获得正确的结果吗?
解决方案
我已经实现了一个 try-catch 循环,并发现一行损坏的数据是问题的根源。这似乎是由于程序的服务器套接字部分,所以我不会在这里进一步讨论,但是 try-catch 循环是一个很好的解决方案,可以找到问题发生的位置,并允许程序继续尽管发生错误。
推荐阅读
- js-cookie - 使用js-cookie库时没有定义cookies
- java - 为什么这个简单的连接代码不能只连接到某个网站?
- java - 在 Eclipse 中搜索包含特定单词的 java 文件,如 Intellij?
- python-3.x - 如何计算带有多列的 pandas 中的(非自)相关矩阵?
- spring - 带有日期的Spring数据mongodb搜索
- python - 在 settings.py Django 中从模型加载数据
- regex - 逗号分隔列表中的唯一值/多列中的唯一值
- html - CSS Import Font-face 区别
- java - org.mockito.exceptions.misusing.InvalidUseOfMatchersException' 异常
- c# - 限制来自 API 的 JSON 字符串响应以选择属性