C#在Unity游戲開發(fā)中進(jìn)行多線程編程的方法
在這之前,有很多人在質(zhì)疑Unity支不支持多線程,事實(shí)上Unity是支持多線程的。而提到多線程就要提到Unity非常常用的協(xié)程,然而協(xié)程并非真正的多線程。協(xié)程其實(shí)是等某個操作完成之后再執(zhí)行后面的代碼,或者說是控制代碼在特定的時機(jī)執(zhí)行。而多線程在Unity渲染和復(fù)雜邏輯運(yùn)算時可以高效的使用多核CPU,幫助程序可以更高效的運(yùn)行。本篇主要介紹在Unity中如何使用多線程。
首先引入C#中使用多線程的類庫
using System.Threading;
創(chuàng)建線程實(shí)例的四種方式
一、線程執(zhí)行無參方法
構(gòu)造語法
// 初始化 Thread 類的新實(shí)例。 // < param name="start">無參委托對象.</ param> public Thread(ThreadStart start)
start
類型:System.Threading.ThreadStart
表示開始執(zhí)行此線程時要調(diào)用的方法的 ThreadStart 委托。
void Start() { //創(chuàng)建無參線程對象 Thread thr = new Thread(Func_NoArguments); //啟動線程 thr.Start(); } // Function Of No Arguments. void Func_NoArguments() { Debug.Log("Run Func_NoArguments"); }
二、線程執(zhí)行有參方法
構(gòu)造語法
// 初始化 Thread 類的新實(shí)例。 // < param name="start">有參委托對象.< /param> public Thread(ParameterizedThreadStart start)
start
類型:System.Threading.ParameterizedThreadStart
一個委托,它表示此線程開始執(zhí)行時要調(diào)用的方法。
注意:參數(shù)只能有一個,且必須為object類型
實(shí)例
void Start() { //創(chuàng)建有參線程對象 Thread thr = new Thread(Func_Arguments); //啟動線程,傳入?yún)?shù) thr.Start("Lanou"); } // Function Of Have Arguments. void Func_Arguments(object data) { Debug.Log("Run Func_Arguments, Data = " + data); }
三、線程執(zhí)行無參方法,限制線程要使用的最大堆棧大小
構(gòu)造語法
// 初始化 Thread 類的新實(shí)例。 // < param name="start">無參委托對象.< /param> // < param name="maxStackSize">使用的最大堆棧大小.< /param> public Thread(ThreadStart start,int maxStackSize)
start
類型:System.Threading.ThreadStart
表示開始執(zhí)行此線程時要調(diào)用的方法的 ThreadStart 委托。
maxStackSize
類型:System.Int32
線程要使用的最大堆棧大小(以字節(jié)為單位);如果為 0,則使用可執(zhí)行文件的文件頭中指定的默認(rèn)最大堆棧大小。
重要事項(xiàng):對于部分受信任的代碼,如果 maxStackSize 大于默認(rèn)堆棧大小,則將其忽略。 不引發(fā)異常。
void Start() { //創(chuàng)建無參線程對象,限制256KB堆棧大小 Thread thr = new Thread(Func_NoArguments,262144); //啟動線程 thr.Start(); } // Function Of No Arguments. void Func_NoArguments() { Debug.Log("Run Func_NoArguments"); }
四、線程執(zhí)行有參方法,限制線程要使用的最大堆棧大小
構(gòu)造語法
// 初始化 Thread 類的新實(shí)例。 // < param name="start">有參委托對象.< /param> // < param name="maxStackSize">使用的最大堆棧大小.< /param> public Thread(ParameterizedThreadStart start,int maxStackSize)
start
類型:System.Threading.ParameterizedThreadStart
一個委托,它表示此線程開始執(zhí)行時要調(diào)用的方法。
注意:參數(shù)只能有一個,且必須為object類型
maxStackSize
類型:System.Int32
線程要使用的最大堆棧大?。ㄒ宰止?jié)為單位);如果為 0,則使用可執(zhí)行文件的文件頭中指定的默認(rèn)最大堆棧大小。
重要事項(xiàng):對于部分受信任的代碼,如果 maxStackSize 大于默認(rèn)堆棧大小,則將其忽略。 不引發(fā)異常。
實(shí)例
void Start() { //創(chuàng)建有參線程對象,限制256KB堆棧大小 Thread thr = new Thread(Func_Arguments,262144); //啟動線程,傳入?yún)?shù) thr.Start("Lanou"); } // Function Of Have Arguments. void Func_Arguments(object data) { Debug.Log("Run Func_Arguments, Data = " + data); }
啟動線程(上文已使用)
無參啟動
void Start() { //創(chuàng)建無參線程對象 Thread thr = new Thread(Func_NoArguments); //啟動線程 thr.Start(); } // Function Of No Arguments. void Func_NoArguments() { Debug.Log("Run Func_NoArguments"); }
有參啟動
void Start() { //創(chuàng)建有參線程對象 Thread thr = new Thread(Func_Arguments); //啟動線程,傳入?yún)?shù) thr.Start("Lanou"); } // Function Of Have Arguments. void Func_Arguments(object data) { Debug.Log("Run Func_Arguments, Data = " + data); }
常用方法
1.public static void Sleep( int millisecondsTimeout)將當(dāng)前線程掛起指定的毫秒數(shù)。
(1)millisecondsTimeout
類型:System.Int32
掛起線程的毫秒數(shù)。 如果 millisecondsTimeout 參數(shù)的值為零,則該線程會將其時間片的剩余部分讓給任何已經(jīng)準(zhǔn)備好運(yùn)行的、有同等優(yōu)先級的線程。 如果沒有其他已經(jīng)準(zhǔn)備好運(yùn)行的、具有同等優(yōu)先級的線程,則不會掛起當(dāng)前線程的執(zhí)行。
(2)public void Resume()
繼續(xù)已掛起的線程。(已過時)
(3)public void Abort()
在調(diào)用此方法的線程上引發(fā) ThreadAbortException,以開始終止此線程的過程。 調(diào)用此方法通常會終止線程。
(4)public void Join()
阻止調(diào)用線程直到線程終止,同時繼續(xù)執(zhí)行標(biāo)準(zhǔn)的 COM 和 SendMessage 傳送。
(5)public enum ThreadPriority
指定 Thread 的調(diào)度優(yōu)先級。
通過線程池執(zhí)行線程
2.ThreadPool.QueueUserWorkItem 方法 (WaitCallback)
public static bool QueueUserWorkItem(WaitCallback callBack)
callBack
類型:System.Threading.WaitCallback
一個 WaitCallback,表示要執(zhí)行的方法。
返回值
類型:System.Boolean
如果此方法成功排隊,則為 true;如果無法將該工作項(xiàng)排隊,則引發(fā) NotSupportedException。
Unity使用多線程注意
變量都是共享的(都能指向相同的內(nèi)存地址)
UnityEngine的API不能在分線程運(yùn)行
UnityEngine定義的基本結(jié)構(gòu)(int,float,Struct定義的數(shù)據(jù)類型)可以在分線程計算,如 Vector3(Struct)可以 , 但Texture2d(class,根父類為Object)不可以。
UnityEngine定義的基本類型的函數(shù)可以在分線程運(yùn)行
Unity多線程插件
LOOM Multi Threading Framework 1.7
核心方法
// Unlike "StartMultithreadedWorkloadExecution", you will have to build your own IThreadWorkerObject. // Downside: It requires some extra work. Upside: you got more controll over what goes in and comes out // Infact: You can create you own polymorphed IThreadWorkerObject-array, each ellement being a completely different type. For example: the statemachines of enemies are IThreadWorkerObject's and the array contains completely different classes with enemies/AI-behaviours. // < param name="workerObjects">An array of IThreadWorkerObject objects to be handled by the threads. If you want multiple cores/threads to be active, make sure that the number of IThreadWorkerObject's proves matches/exeeds your preferred number maxWorkingThreads. < /param> // < param name="onComplete">Fired when all re-packaged workLoad-objects are finished computing< /param> // < param name="onPackageExecuted">Fires foreach finished re-packaged set of workLoad-object< /param> // < param name="maxThreads"> Lets you choose how many threads will be run simultaneously by the threadpool. Default: -1 == number of cores minus one, to make sure the MainThread has at least one core to run on. (quadcore == 1 core Mainthread, 3 cores used by the ThreadPoolScheduler)< /param> // < param name="scheduler">If Null, a new ThreadPoolScheduler will be instantiated.< /param> // < param name="safeMode">Executes all the computations within try-catch events, logging it the message + stacktrace< /param> // < returns>A ThreadPoolScheduler that handles all the repackaged workLoad-Objects< /returns> public static ThreadPoolScheduler StartMultithreadedWorkerObjects(IThreadWorkerObject[] workerObjects, ThreadPoolSchedulerEvent onCompleteCallBack, ThreadedWorkCompleteEvent onPackageExecuted = null, int maxThreads = -1, ThreadPoolScheduler scheduler = null, bool safeMode = true) { if (scheduler == null) scheduler = CreateThreadPoolScheduler(); scheduler.StartASyncThreads(workerObjects, onCompleteCallBack, onPackageExecuted, maxThreads, safeMode); return scheduler; }
結(jié)束語
Unity可以使用多線程,但對其有很多限制,所以在不使用UnityEngine API的情況下,可以使用多線程,提高多核CPU的使用率。通??梢詫⑿枰罅坑嬎愕乃惴▋?nèi)容,放置到多線程中執(zhí)行,包括邏輯框架也可以放到多線程中執(zhí)行。本篇理論性較強(qiáng),后期會陸續(xù)發(fā)布實(shí)戰(zhàn)型文章。
相關(guān)文章
Unity3d實(shí)現(xiàn)無限循環(huán)滾動背景
這篇文章主要為大家詳細(xì)介紹了Unity3d實(shí)現(xiàn)無限循環(huán)滾動背景,一個完整的商店廣告牌組件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01C# Dynamic關(guān)鍵字之:解析dynamic就是Object
本篇文章是對C#中dynamic關(guān)鍵字就是Object進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05C#中的modbus Tcp協(xié)議的數(shù)據(jù)抓取和使用解析
這篇文章主要介紹了C#中的modbus Tcp協(xié)議的數(shù)據(jù)抓取和使用解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07