Unity calls the main thread's method in a child thread

In Unity, calling the main thread method in a child thread can be achieved by using the main thread task queue provided by Unity. This can be accomplished by following these steps:

1. Define a delegate type and declare the methods that need to be executed in the main thread.

public delegate void MainThreadAction();

2. Create a main thread task queue, run in the main thread, to store methods that need to be executed in the main thread.

public static class MainThreadTaskQueue
{
    
    
    private static readonly Queue<MainThreadAction> tasks = new Queue<MainThreadAction>();
    private static readonly object queueLock = new object();

    public static void EnqueueTask(MainThreadAction action)
    {
    
    
        lock (queueLock)
        {
    
    
            tasks.Enqueue(action);
        }
    }

    public static void ExecuteTasks()
    {
    
    
        lock (queueLock)
        {
    
    
            while (tasks.Count > 0)
            {
    
    
                var task = tasks.Dequeue();
                task?.Invoke();
            }
        }
    }
}

3. Use the main thread task queue in the child thread to call methods that need to be executed in the main thread.

// 示例子线程方法
private void SomeBackgroundThreadMethod()
{
    
    
    // 在子线程中添加任务到主线程任务队列
    MainThreadTaskQueue.EnqueueTask(() =>
    {
    
    
        // 这里是需要在主线程中执行的代码
        MyMethod();
    });
}

// 在主线程 Update 或其他适当的地方执行主线程任务队列中的方法
private void Update()
{
    
    
    MainThreadTaskQueue.ExecuteTasks();
}

Note : It should be noted that since most of Unity's APIs can only be called in the main thread, when calling across threads, the code that needs to be executed in the main thread needs to be wrapped in a delegate and passed through the main thread. Task queue for scheduling execution. In addition, make sure to call the ExecuteTasks method of the main thread task queue at the appropriate place in the main thread (such as the Update method) in order to execute the tasks in the queue.

Guess you like

Origin blog.csdn.net/weixin_44446603/article/details/133325125