c# - 使用 C# 统一线程以进行优化
问题描述
所以这是我的代码:想法是在输入系统类中我们从用户那里找到一些数据,然后从线程类中监听这些数据并在一个新线程中处理它,然后我们将处理后的数据返回到主线程.
它有效,但速度很慢......这是为什么呢?
我是编码新手,所以希望能解释错误......
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Threading;
public class InputSystem : MonoBehaviour
{
public EventHandler<dataStore> onRequest;
public class dataStore : EventArgs
{
public int[] dataPass;
}
public int[] newData;
void Start()
{
int[] test = new int[] { 6, 6, 6 };
newData = test;
}
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
onRequest?.Invoke(this, new dataStore { dataPass = newData });
}
}
}
public class StartThread : MonoBehaviour
{
void Start()
{
InputSystem input = GetComponent<InputSystem >();
input.onRequest += findPath;
}
requestData pData;
returnData rData;
public void findPath(object sender, InputSystem.dataStore data)
{
pData = data.dataToPass;
RequestPath(method);
}
public static void RequestPath(Action doThing)
{
ThreadStart thread = delegate
{
doThing();
};
thread.Invoke();
}
public Queue<Action> toRun = new Queue<Action>();
public void method()
{
PathAlg test = new PathAlg();
Action toQueue = () =>
{
requestData data = pData;
rData.data = test.method(data);
};
lock (toRun)
{
toRun.Enqueue(toQueue);
}
}
void Update()
{
while (toRun.Count > 0)
{
lock (toRun)
{
Action runThis = toRun.Dequeue();
runThis();
foreach(int n in rData)
{
print(n);
}
}
}
}
}
public struct requestData
{
public int[] data;
}
public struct returnData
{
public int[] data;
}
public class pathAlg
{
public int[] method(requestData data)
{
int[] example = new int[data.Length];
for(int i = 0; i< example.Length; i++)
{
example[i] = i+1;
}
return example;
}
}
解决方案
通过使用协程而不是线程解决了这个问题。
推荐阅读
- java - 在 pyspark 中从外部 Java jar 类注册 UDF
- vba - 如何在单独的函数中编写电子邮件正文?
- javascript - 使用 OOP js 推入数组
- azure - 首次通过 RDP 访问 Azure 虚拟机,在命令提示符处停止
- node.js - 使用命令“Docker container run”后,我的容器没有显示
- python - 用另一种语言解压pythons struct.pack
- java - 如何将导航抽屉切换添加到工具栏
- javascript - 使用 SwitchNavigator 在导航器之间切换(反应导航)
- python - 下载 Python 的第 3 方源代码
- php - 如何为具有变体和简单产品的产品添加“立即购买”