将收到的数据快速的和主程序中的数据进行交互,无需通过队列作为中转。
解决当队列包中数据较多时,数据处理不及时会产生的延迟问题。
using System.Threading;
using UnityEngine;
public class SceneController : MonoBehaviour
{
private Transform _cube;
private SynchronizationContext _context;
private void Start()
{
_cube = GameObject.Find("Cube").transform;
_context = SynchronizationContext.Current;
}
private void SetPos(Vector3 pos)
{
Thread.Sleep(2000);
_cube.position = pos;
}
private void OnGUI()
{
if (GUI.Button(new Rect(10, 50, 100, 30), "Post"))
{
Thread thread = new Thread(new ThreadStart(() =>
{
//将Function以异步的方式传递到主线程中,无需等待Function完成,即可运行后续代码
_context.Post((function => { SetPos(new Vector3(0, 0, 0)); }), null);
//线程等待循环
//SpinWait.SpinUntil(() => _updateJointValuePack.IsComplete);
}));
thread.Start();
}
if (GUI.Button(new Rect(10, 100, 100, 30), "Send"))
{
Thread thread = new Thread(new ThreadStart(() =>
{
//将Function以同步的方式传递到主线程中,需等待Function完成后可运行后续代码
_context.Send((function => { SetPos(new Vector3(10, 0, 0)); }), null);
}));
thread.Start();
}
}
}