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类有一个带参数的委托类型的重载形式,这 ...
随机推荐
- Ubuntu 安装Sqldeveloper
linux下最好用的Oracle开发工具可能就是sqldeveloper了 首先在http://otn.oracle.com/ 上下载最新的Linux - sqldeveloper 我下载的时候版本是 ...
- 分享自己使用的在线UML画图工具
刚接触UML时间不长,看了N多教学视频,下载好了几个软件各种不习惯 当我遇见了ProcessOn 从此我彻底“爱上”了它! http://www.processon.com/ UML各类例图它几乎全 ...
- Windows核心编程:第11章 Windows线程池
Github https://github.com/gongluck/Windows-Core-Program.git //第11章 Windows线程池.cpp: 定义应用程序的入口点. // #i ...
- 【BZOJ4755】 [Jsoi2016]扭动的回文串
BZOJ4755 [Jsoi2016]扭动的回文串 Solution 考虑对于他给出的 A中的一个回文串: B中的一个回文串: 或者某一个回文的扭动字符串S(i,j,k) 这样子几个限制,我们1,2就 ...
- SpringCloud之Eureka集群
前面我们介绍了SpringCloud注册中心Eureka,但是存在一个单点故障的问题,一个注册中心远远不能满足实际的生产环境,现在我们介绍一下如何搭建一个Eureka集群. 一:集群环境搭建 我们先建 ...
- Git - 信息查看
git help git version # Display the version of git. git help # Prints the synopsis and a list of the ...
- 使用Nginx转发TCP/UDP数据
编译安装Nginx 从1.9.0开始,nginx就支持对TCP的转发,而到了1.9.13时,UDP转发也支持了.提供此功能的模块为ngx_stream_core.不过Nginx默认没有开启此模块,所以 ...
- POJ 2771
#include <iostream> #include <string> #define MAXN 505 using namespace std; int _m[MAXN] ...
- RVM的安装和使用过程中碰到的问题
Ruby Version Manager简称RVM,是一款非常好用的ruby版本管理以及安装工具. 关于rvm的安装,可以参考以下文章: use rvm install and manage ruby ...
- React VR 技术开发群 579149907
React VR 技术开发群 579149907,欢迎加入讨论!分享经验!