首页 > 解决方案 > 使用 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;
    }
    
}

标签: c#multithreading

解决方案


通过使用协程而不是线程解决了这个问题。


推荐阅读