Unity多线程使用(线程池)

1.在C#中使用线程池需要以下这个类库using System.Threading

2.开单个线程(unity程序停止前 线程一定要关闭)

    private Thread tempThread;
    void Start () {
        tempThread = new Thread(MyThread);//将方法注册到线程句柄当中,注意保留这个句柄,最后需要关闭线程,要不然会造成unity停止运行线程不停止。
        tempThread.Start();//开启线程。
    }
    //这是线程方法
    private void MyThread()
    {
        Debug.Log("开了线程");
    }

关闭线程(Thread.Abort();)

3.线程池的使用

线程池相对于线程而言更加方便,在线程池中的线程是由系统进行统一管理,我们在使用的过程中不需要自己去对线程进行开关操作,这些系统都会给我们做了。而且线程池还有一个好处,就是可以传参!

    private int m_iParam;//随便一个类型的参数
    void Start () {
        ThreadPool.QueueUserWorkItem(new WaitCallback(MyThread), m_iParam);//将方法添加进线程池,并传入参数
    }
    private void MyThread(object param)
    {
        Debug.Log("开了线程");
    }

也可以封装成方法

//线程池上的队列
    public static void QueueOnThreadPool(WaitCallback callBack, object state = null)
    {
        ThreadPool.QueueUserWorkItem(callBack, state);
    }

c#脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
using System;

public class XianCheng : MonoBehaviour
{
    public static XianCheng Current;
    static Thread mainthread;  //主线程
    private List<Action> actions = new List<Action>();  //
    public int[]tssd=new int [30];
    public bool bol = false;
      
    public static bool IsMainThread()
    {
        return Thread.CurrentThread == mainthread;
    }
    private void Awake()
    {
        Current = this;
        mainthread = Thread.CurrentThread;
        bol = true;
    }
    private void OnDestroy()
    {
        mainthread.Abort();
        bol = false;
    }
 void Start()
    {
        QueueOnThreadPool((Func_0), 0);
    }
void Update() { var currentActions = new List<Action>(); lock (actions) { currentActions.AddRange(actions); foreach (var item in currentActions) actions.Remove(item); } } //主线程上的队列 public static void QueueOnMainThread(Action action) { if (IsMainThread()) { action(); return; } lock (Current.actions) { Current.actions.Add(action); } } //线程池上的队列 public static void QueueOnThreadPool(WaitCallback callBack, object state = null) { ThreadPool.QueueUserWorkItem(callBack, state); } }
 void Func_0(object parm)
    {
        try
        {
            while (bol)
            {
                tssd[0] += 1;
                Thread.Sleep(100);
            }
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
           
        }
    }

 

posted @ 2022-02-09 17:31  剑起苍穹  阅读(3489)  评论(0编辑  收藏  举报
/*鼠标点击特效*/