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); } }