unity3d 線程安全問題c#
gui相關的操做必須在Update 裏調用,因此通常的解決辦法是使用一個隱藏的MonoBehaviour,非UI線程裏想作的操做都註冊到這個隱藏的MonoBehaviour裏安全
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace wlgame { public delegate void GUITask (); public class TaskExecutorScript : MonoBehaviour { private Queue<GUITask> TaskQueue = new Queue<GUITask> (); private object _queueLock = new object (); // Update is called once per frame void Update () { lock (_queueLock) { if (TaskQueue.Count > 0) TaskQueue.Dequeue () (); } } public void ScheduleTask (GUITask newTask) { lock (_queueLock) { if (TaskQueue.Count < 100) TaskQueue.Enqueue (newTask); } } } }
AfterResponseFuntion afterFun = delegate(System.Object result) { taskExecutor.ScheduleTask (new GUITask (delegate { EditorUtility.DisplayDialog ("title", "aaaaaaa", "abc", "edf"); })); }; Communication.SendScore2Server (afterFun);