1.在C#中使用线程池需要以下这个类库using System.Threading
2.开单个线程(unity程序停止前 线程一定要关闭),要不然会崩溃
关闭线程(Thread.Abort();)
3.创建线程
private Thread tempThread;
void Start () {
tempThread = new Thread(MyThread);//将方法注册到线程句柄当中,注意保留这个句柄,最后需要关闭线程,要不然会造成unity停止运行线程不停止。
tempThread.Start();//开启线程。
}
//这是线程方法
private void MyThread()
{
Debug.Log("开了线程");
}
4.完整的代码如下:
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);
}
}
自行测试即可