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

最新文章

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

热门文章

  1. GP232RL国产USB串口如何兼容FT232RL开发资料
  2. 微服务笔记之Eureka(1)
  3. PY0271验证码的创建
  4. ubuntu fastdds安装
  5. (三)用go实现平衡二叉树
  6. springboot整合mybatis以及mybatis源码分析
  7. ES-索引库
  8. uniapp 小程序自定义组件样式穿透问题
  9. 《Makefile中DEP_LIBRARIES变量的作用》
  10. Vue 数组响应