/************************************************************************* * 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 mCurrentActions = new List(); List mActions = new List(); 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](); } } } }