U3DC.COM | 优三帝研究院

Menu

简易实现Unity多线程解决方案

建议和异步任务模型 System.Threading.Tasks 配合使用。

using UnityEngine;
using System.Collections.Generic;
using System;
using System.Threading;

public class ThreadHelper : MonoBehaviour
{
    private static ThreadHelper Current;

    private List actions = new List();

    private static Thread mainThread;

    public static bool IsMainThread()
    {
        return Thread.CurrentThread == mainThread;
    }

    // Use this for initialization
    void Awake()
    {
        Current = this;

        mainThread = Thread.CurrentThread;
    }

    // Update is called once per frame
    void Update()
    {
        var currentActions = new List();

        lock (actions)
        {
            currentActions.AddRange(actions);
            foreach (var item in currentActions)
                actions.Remove(item);
        }

        foreach (var action in currentActions)
        {
            action();
        }
    }

    public static void QueueOnMainThread(Action action)
    {
        if(IsMainThread())
        {
            action();
            return;
        }

        lock (Current.actions)
        {
            Current.actions.Add(action);
        }
    }
}
打赏
— 于 共写了757个字
— 文内使用到的标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据