PagedLodThreadPool.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*************************************************************************
  2. * Copyright © 2018-2023 Liwen All rights reserved.
  3. *------------------------------------------------------------------------
  4. * File : PagedLodThreadPool.cs
  5. * Description : Load tile file with threadpool
  6. *------------------------------------------------------------------------
  7. * Author : Liwen
  8. * Version : 1.0.0
  9. * Date : 1/5/2019
  10. * Description : Initial development version.
  11. *************************************************************************/
  12. using UnityEngine;
  13. using System.Collections;
  14. using System.Collections.Generic;
  15. using System;
  16. using System.Threading;
  17. using System.Linq;
  18. namespace AIPagedLod
  19. {
  20. public class PagedLodThreadPool : MonoBehaviour
  21. {
  22. static PagedLodThreadPool mCurrentPoll;
  23. static int mNumThreads;
  24. List<Action> mCurrentActions = new List<Action>();
  25. List<Action> mActions = new List<Action>();
  26. void Start()
  27. {
  28. mCurrentPoll = this;
  29. ThreadPool.SetMaxThreads(PagedLodConfig.mThreadCount, PagedLodConfig.mThreadCount);
  30. }
  31. public static void QueueOnMainThread(Action action)
  32. {
  33. lock (mCurrentPoll.mActions)
  34. {
  35. mCurrentPoll.mActions.Add(action);
  36. }
  37. }
  38. public static bool IsQueueWorkItem()
  39. {
  40. if (!PagedLodUpdateController.IsUpdateEnabled())
  41. {
  42. return false;
  43. //return mNumThreads < 1;
  44. }
  45. return mNumThreads < PagedLodConfig.mThreadCount;
  46. }
  47. public static Thread RunAsync(Action a)
  48. {
  49. ThreadPool.QueueUserWorkItem(RunAction, a);
  50. Interlocked.Increment(ref mNumThreads);
  51. return null;
  52. }
  53. private static void RunAction(object action)
  54. {
  55. try
  56. {
  57. ((Action)action)();
  58. }
  59. catch
  60. {
  61. }
  62. finally
  63. {
  64. Interlocked.Decrement(ref mNumThreads);
  65. }
  66. }
  67. void OnDisable()
  68. {
  69. if (mCurrentPoll == this)
  70. {
  71. mCurrentPoll = null;
  72. }
  73. }
  74. void Update()
  75. {
  76. lock (mActions)
  77. {
  78. mCurrentActions.Clear();
  79. mCurrentActions.AddRange(mActions);
  80. mActions.Clear();
  81. }
  82. for (int i = 0; i < mCurrentActions.Count; ++i)
  83. {
  84. mCurrentActions[i]();
  85. }
  86. }
  87. }
  88. }