| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 | /************************************************************************* *  Copyright © 2018-2023 Liwen All rights reserved. *------------------------------------------------------------------------ *  File         :  PagedLodThreadPool.cs *  Description  :  Load tile file with threadpool *------------------------------------------------------------------------ *  Author       :  Liwen *  Version      :  1.0.0 *  Date         :  1/5/2019 *  Description  :  Initial development version. *************************************************************************/using UnityEngine;using System.Collections;using System.Collections.Generic;using System;using System.Threading;using System.Linq;namespace AIPagedLod{    public class PagedLodThreadPool : MonoBehaviour    {        static PagedLodThreadPool mCurrentPoll;        static int mNumThreads;        List<Action> mCurrentActions = new List<Action>();        List<Action> mActions = new List<Action>();        void Start()        {            mCurrentPoll = this;            ThreadPool.SetMaxThreads(PagedLodConfig.mThreadCount, PagedLodConfig.mThreadCount);        }        public static void QueueOnMainThread(Action action)        {            lock (mCurrentPoll.mActions)            {                mCurrentPoll.mActions.Add(action);            }        }        public static bool IsQueueWorkItem()        {            if (!PagedLodUpdateController.IsUpdateEnabled())            {                return false;                //return mNumThreads < 1;            }            return mNumThreads < PagedLodConfig.mThreadCount;        }        public static Thread RunAsync(Action a)        {            ThreadPool.QueueUserWorkItem(RunAction, a);            Interlocked.Increment(ref mNumThreads);            return null;        }        private static void RunAction(object action)        {            try            {                ((Action)action)();            }            catch            {            }            finally            {                Interlocked.Decrement(ref mNumThreads);            }        }        void OnDisable()        {            if (mCurrentPoll == this)            {                mCurrentPoll = null;            }        }        void Update()        {            lock (mActions)            {                mCurrentActions.Clear();                mCurrentActions.AddRange(mActions);                mActions.Clear();            }            for (int i = 0; i < mCurrentActions.Count; ++i)            {                mCurrentActions[i]();            }             }    }}
 |