Unity主线程和子线程跳转调用(1)
Unity除了一些基本的数据类型,几乎所有的API都不能在非unity线程中调用,如果项目中有一段很耗时操作,unity可能会出现“假死”。如果这段操作是和unity无关的,我们可以把这个耗时的操作放到子线程中去运行,防止unity假死提高性能,如下面这个伪代码
Function
{
//这个函数会进行大量文件读写操作
LoadLocalFile(); //这个函数是unity函数
UnityFunction();
}
必须保证LoadLocalFile() 不“假死”。怎么做呢?只要把Function放到多线程中,UnityFunction()回到主线程即可
网上的做法一般都是借鉴Loom,摘录一个脚本
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Threading;
using System.Linq; public class Loom :MonoBehaviour
{
public static int maxThreads = ;
static int numThreads; private static Loom _current;
//private int _count;
public static Loom Current
{
get
{
Initialize();
return _current;
}
} void Awake()
{
_current = this;
initialized = true;
} static bool initialized; public static void Initialize()
{
if (!initialized)
{ if (!Application.isPlaying)
return;
initialized = true;
var g = new GameObject("Loom");
_current = g.AddComponent<Loom>();
#if !ARTIST_BUILD
UnityEngine.Object.DontDestroyOnLoad(g);
#endif
} }
public struct NoDelayedQueueItem
{
public Action<object> action;
public object param;
} private List<NoDelayedQueueItem> _actions = new List<NoDelayedQueueItem>();
public struct DelayedQueueItem
{
public float time;
public Action<object> action;
public object param;
}
private List<DelayedQueueItem> _delayed = new List<DelayedQueueItem>(); List<DelayedQueueItem> _currentDelayed = new List<DelayedQueueItem>(); public static void QueueOnMainThread(Action<object> taction, object tparam)
{
QueueOnMainThread(taction, tparam, 0f);
}
public static void QueueOnMainThread(Action<object> taction, object tparam, float time)
{
if (time != )
{
lock (Current._delayed)
{
Current._delayed.Add(new DelayedQueueItem { time = Time.time + time, action = taction, param = tparam });
}
}
else
{
lock (Current._actions)
{
Current._actions.Add(new NoDelayedQueueItem { action = taction, param = tparam });
}
}
} public static Thread RunAsync(Action a)
{
Initialize();
while (numThreads >= maxThreads)
{
Thread.Sleep();
}
Interlocked.Increment(ref numThreads);
ThreadPool.QueueUserWorkItem(RunAction, a);
return null;
} private static void RunAction(object action)
{
try
{
((Action)action)();
}
catch
{
}
finally
{
Interlocked.Decrement(ref numThreads);
} } void OnDisable()
{
if (_current == this)
{ _current = null;
}
} // Use this for initialization
void Start()
{ } List<NoDelayedQueueItem> _currentActions = new List<NoDelayedQueueItem>(); // Update is called once per frame
void Update()
{
if (_actions.Count > )
{
lock (_actions)
{
_currentActions.Clear();
_currentActions.AddRange(_actions);
_actions.Clear();
}
for (int i = ; i < _currentActions.Count; i++)
{
_currentActions[i].action(_currentActions[i].param);
}
} if (_delayed.Count > )
{
lock (_delayed)
{
_currentDelayed.Clear();
_currentDelayed.AddRange(_delayed.Where(d => d.time <= Time.time));
for (int i = ; i < _currentDelayed.Count; i++)
{
_delayed.Remove(_currentDelayed[i]);
}
} for (int i = ; i < _currentDelayed.Count; i++)
{
_currentDelayed[i].action(_currentDelayed[i].param);
}
}
}
}
使用方式
Function
{
//异步在多线程下运行
Loom.RunAsync(() =>
{
//这个函数会进行大量文件读写操作
LoadLocalFile(); //回到unity线程继续运行
Loom.QueueOnMainThread(()=>
{
//这个函数是unity函数
UnityFunction();
}
}
}
这个Loom类的大概思路就是把整个代码块放多线程中,并把需要在主线程运行的代码按委托的方式封装起来保存的list里,Updata函数是unity函数,他会自动每帧执行一次。所以他可以判断list是否有任务并执行任务,从而实现了回到主线程
Unity主线程和子线程跳转调用(1)的更多相关文章
- Unity主线程和子线程跳转调用(2)
在上一篇介绍了多线程和Unity交互方式,但是由于我的项目是一个unity编辑器插件项目,很显然上一篇的代码需要加以修改,在编辑器下实现Loom. 1,Editor下的没有Update这个生命周期函数 ...
- UNIX环境高级编程——主线程与子线程的退出关系
我们在一个线程中经常会创建另外的新线程,如果主线程退出,会不会影响它所创建的新线程呢?下面就来讨论一下. 1. 主线程等待新线程先结束退出,主线程后退出.正常执行. 示例代码: #include & ...
- Android线程之主线程向子线程发送消息
和大家一起探讨Android线程已经有些日子了,谈的最多的就是如何把子线程中的数据发送给主线程进行处理,进行UI界面的更新,为什么要这样,请查阅之前的随笔.本篇我们就来讨论一下关于主线程向子线程如何发 ...
- (转)C#/.NET主线程与子线程之间的关系
一般 一个应用程序就对应一个进程,一个进程可有一个或多个线程,而一般有一个主线程. 有的博客上说“至少一个主线程”,这一说法持有怀疑 主线程与子线程之间的关系 ...
- Handler详解系列(四)——利用Handler在主线程与子线程之间互发消息,handler详解
MainActivity如下: package cc.c; import android.app.Activity; import android.os.Bundle; import android. ...
- C#主线程等待子线程运行结束
佐左佑右 原文 C#主线程等待子线程运行结束 由于主程序中调用matlab的dll文件进行计算要用较长的时间,主界面会有很长时间的卡顿,造成的用户感受十分不好,因此我想在调用时,将调用放入子线程中,然 ...
- Handler具体解释系列(四)——利用Handler在主线程与子线程之间互发消息
MainActivity例如以下: package cc.c; import android.app.Activity; import android.os.Bundle; import androi ...
- Java主线程等待子线程、线程池
public class TestThread extends Thread { public void run() { System.out.println(this.getName() + &qu ...
- [C#参考]主线程和子线程之间的参数传递
几个进程在大多数情况下要包含很多的子线程,那么他们之间免不了的要互相传递很多的参数,那么参数怎么传递的呢? 主线程向子线程传递参数的方法 第一种方法:Thraed类有一个带参数的委托类型的重载形式,这 ...
随机推荐
- 利用C#迭代器的一个杨辉三角示例
身边有个朋友在跟着廖雪峰的教程学习python,途中遇到了"在Python中使用迭代器打印杨辉三角"的问题,我在帮忙解决的同时顺手写了个简单的C#版本以供补充. internal ...
- python实现Telnet远程登陆到设备并执行命令
#encoding=utf-8 import telnetlib import time def do_telnet(Host, username, password, finish, command ...
- MariaDB 插入&更新&删除数据(8)
MariaDB数据库管理系统是MySQL的一个分支,主要由开源社区在维护,采用GPL授权许可MariaDB的目的是完全兼容MySQL,包括API和命令行,MySQL由于现在闭源了,而能轻松成为MySQ ...
- Python 一篇学会多线程
多线程和多进程是什么自行google补脑,廖雪峰官网也有,但是不够简洁,有点晕,所以就整个简单的范例. 对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂.所以,这里力图用 ...
- 对股市骗子内部的一次apt测试
i春秋作家:jasonx 前言 由于这件事情搞了很久,中间很多截图已经没有了,所以文章中出现的部分截图是后面截的. 文中很多地方涉及敏感信息,为了我的人身安全,打码比较严重,还请多多理解. 起因 前不 ...
- Shell - 简明Shell入门12 - 定制输出(ColorOutput)
示例脚本及注释 #!/bin/bash echo -e "\033[32m" # 设置输出属性,绿色字体 echo "This is a test!" echo ...
- POJ 2864
#include <iostream> #define MAXN 600 using namespace std; int _m[MAXN][MAXN]; int main() { //f ...
- oracle 用户权限相关
--查看数据库下的所有用户: select username from dba_users; --查看当前连接数据库的用户角色 SELECT * FROM USER_ROLE_PRIVS; -- 创建 ...
- 集成学习算法总结----Boosting和Bagging
1.集成学习概述 1.1 集成学习概述 集成学习在机器学习算法中具有较高的准去率,不足之处就是模型的训练过程可能比较复杂,效率不是很高.目前接触较多的集成学习主要有2种:基于Boosting的和基于B ...
- 修改vs2012 颜色
http://bbs.pcbeta.com/viewthread-1265615-1-1.html VS2012的默认深色主题的确让整个IDE看起来很有气场,而且深色的主题保护眼睛,还是蛮不错的. 但 ...