Unity main thread and the child thread Jump calls (2)

In the last introduced multi-threading and Unity interactively, but because my project is an editor plug-in project unity, it is clear that on a code needs to be modified to achieve Loom in the editor.

1, under Editor Update this life is not a periodic function, but Ediitor provides EditorApplication.update this event, they used this method to the event subscription update

2, under the Editor no Awake OnDestory the life cycle of these functions, you need to write your own way to get outside to create, destroy Loom

3, I need to ensure that the project is not logical sub-thread of suspended animation while also ensuring synchronization, such as the following piece of pseudo-code, the order is: DownFile1-> UnityFunction1-> DownFile2-> UnityFunction2

  

Function
{
    // run asynchronously in a multithreaded
    Loom.RunAsync(() =>
    {
                 // consuming function
        DownFile1();

                 // thread continues to run back to unity
        Loom.QueueOnMainThread(()=>
        {    
                         // This function is a function of unity
            UnityFunction1();
        }
        
                 // consuming function
        DownFile2();
                   // thread continues to run back to unity
        Loom.QueueOnMainThread(()=>
        {    
                         // This function is a function of unity
            UnityFunction2();
        }
    
    }
}

  

The modified code as follows

  1 using UnityEngine;
  2 using System.Collections;
  3 using System.Collections.Generic;
  4 using System;
  5 using System.Threading;
  6 using System.Linq;
  7 using UnityEditor;
  8 public class Loom
  9 {
 10     /// <summary>
 11     ///  Are currently unity tasks to be performed
 12     /// </summary>
 13     static bool hasUnityAction = true;
 14 
 15     private static Thread loomThread;
 16 
 17     /// <summary>
 18     ///  unity task list
 19     /// </summary>
 20     private List<Action> actions = new List<Action>();
 21 
 22     #region  Singleton registered update event
 23     private static Loom _instance;
 24     private static readonly object lockObj = new object();
 25     public static Loom Current
 26     {
 27         get
 28         {
 29             if (_instance == null)
 30             {
 31                 lock (lockObj)
 32                 {
 33                     if (_instance == null)
 34                     {
 35                         _instance = new Loom();
 36                     }
 37 
 38                 }
 39             }
 40             return _instance;
 41         }
 42     }
 43     private Loom()
 44     {
 45         EditorApplication.update += Update;
 46 
 47     }
 48     #endregion
 49 
 50 
 51 
 52 
 53     /// <summary>
 54     ///  Child thread start a task
 55     /// </summary>
 56     /// <param name="a"></param>
 57     /// <returns></returns>
 58     public Thread RunAsync(Action a)
 59     {
 60         if (loomThread != null)
 61         {
 62             Stop();
 63             throw new Exception("Task to run only once");
 64         }
 65         loomThread = new Thread(new ParameterizedThreadStart(RunAction));
 66         loomThread.Name = "Loom thread";
 67         loomThread.Priority = System.Threading.ThreadPriority.Lowest;
 68         loomThread.Start(a);
 69         return loomThread;
 70     }
 71     /// <summary>
 72     ///  Add a task to the main thread queue
 73     /// </summary>
 74     /// <param name="action"></param>
 75     public void QueueOnMainThread(Action action)
 76     {
 77         if (Current != null && Thread.CurrentThread == loomThread)
 78         {
 79             hasUnityAction = true;
 80             lock (Current.actions)
 81             {
 82                 Current.actions.Add(action);
 83             }
 84             while (hasUnityAction)
 85             {
 86                 loomThread.Priority = System.Threading.ThreadPriority.Lowest;
 87                 Thread.Sleep(10);
 88             }
 89         }
 90 
 91     }
 92 
 93     /// <summary>
 94     ///  Delayed child thread
 95     /// </summary>
 96     /// <param name="time"></param>
 97     public void Sleep(int time)
 98     {
 99         if (Current != null && Thread.CurrentThread == loomThread)
100         {
101             Thread.Sleep(time);
102 
103         }
104     }
105 
106     /// <summary>
107     ///  Stop the task
108     /// </summary>
109     public void Stop()
110     {
111         EditorApplication.update -= Update;
112         try
113         {
114             loomThread.Abort();
115         }
116         catch (Exception e)
117         {
118             Debug.Log(e.ToString());
119         }
120         finally
121         {
122             loomThread = null;
123             _instance = null;
124         }
125 
126     }
127 
128 
129 
130     private void RunAction(object action)
131     {
132         try
133         {
134             ((Action)action)();
135         }
136         catch
137         {
138         }
139 
140     }
141 
142     List<Action> _currentActions = new List<Action>();
143 
144     static void Update()
145     {
146         try
147         {
148 
149 
150             if (!hasUnityAction) return;
151 
152             lock (Current.actions)
153             {
154                 Current._currentActions.Clear();
155                 Current._currentActions.AddRange(Current.actions);
156                 Current.actions.Clear();
157             }
158             for (int i = 0; i < Current._currentActions.Count; i++)
159             {
160                 Debug.LogError("The main thread task");
161                 Current._currentActions[i]();
162 
163             }
164             hasUnityAction = false;
165         }
166         catch
167         {
168             Debug.LogError("The main thread mission failed");
169         }
170     }
171 }

 

Intelligent Recommendation

Unity C# child thread Action sent to the main thread for execution

I went for an interview today.. The interviewer even said that the action of the child thread cannot be sent to the main thread for execution......

Practice thread || 2 cycles child thread, the main thread 2 cycles, then 2 cycles child thread, the main thread 2 cycles, and 10 cycles;

Subject description: 2 cycles child thread, the main thread 2 cycles, then 2 cycles child thread, the main thread 2 cycles, and 10 cycles; analysis: The purpose two threads, one for sub-loop twice, th...

The main thread calls child thread object's sleep () method will cause the child thread to sleep it?

Foreword Today, when writing threaded test, I wrote the following piece of code } After the results of the test, and did not follow me to perform as expected. I.e., the print of 10 s "main thread...

Child thread and the main thread swap

   Print:   ...

The main thread, the child thread, and join ()

In line to see an example The output is Main thread is finished                    &n...

More Recommendation

java main thread and child thread

In the main function of JAVA, when a child thread is opened, the main thread will execute without waiting for the child thread to execute, but the JVM will exit only after the child thread is executed...

java main thread wait for all child thread is finished executing (2)

original: The total work often run asynchronously to perform certain logic, then to deal with other things, and then processing the results after that part of the logic of aggregated scene, this time ...

The relationship between the main thread and the child thread in the thread

1. In the most common case, a sub-thread is opened in the main thread. After being opened, the main thread and the sub-thread do not affect each other's life cycle, that is, the main thread ends, the ...

UNITY sub-thread and main thread interaction 2 (event listening)

The Unity API cannot be accessed from the sub-thread, but some operations (Example IO Acquisition files) must be running again, so it is implemented in the sub-thread time consumption, and notify the ...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top