Unity多线程使用(线程池)
2024-10-20 04:07:30
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); }
}
最新文章
- FastDFS.Client操作文件服务器
- php array 分页
- HTML 学习笔记 CSS样式(框模型)
- Android drawable的自动缩放
- php比较加赋值语句
- ————————————————————————————杭电ACM————————————————X-POWER————————————————————————————————
- 继承TextView简单画一个尺子
- 降低Java垃圾回收开销的5条建议
- 基于BaseHTTPServer的简单存储服务器
- 批量杀进程——xargs用途
- 交换机access与trunk口
- IEquatable(T) interface in .Net
- Servlet路径映射
- Python Learning - One
- Teradata全面转型
- NTT算法小结
- js判断元素是否是disable状态
- 【Hbase学习之四】Hbase表设计案例
- redis,nodejs,php,pub/sub 实战: 微信语音识别
- windows命令行的使用,去掉";半";字