Advertisement
Guest User

Untitled

a guest
Jan 25th, 2020
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Threading;
  5.  
  6. namespace iGP
  7. {
  8.  
  9. public class ThreadManager
  10. {
  11. ////////////////////////////////////////////////////////////////////////////////////////////////////
  12. //Public nested data structures declaration
  13. ////////////////////////////////////////////////////////////////////////////////////////////////////
  14. public delegate void ThreadCall( object data, Action onResult );
  15.  
  16. private struct ThreadParams
  17. {
  18. public ThreadCall threadCall;
  19. public object data;
  20. public Action onResult;
  21.  
  22. public ThreadParams( ThreadCall threadCall, object data, Action onResult )
  23. {
  24. this.threadCall = threadCall;
  25. this.data = data;
  26. this.onResult = onResult;
  27. }
  28. }
  29.  
  30. ////////////////////////////////////////////////////////////////////////////////////////////////////
  31. //Public methods
  32. ////////////////////////////////////////////////////////////////////////////////////////////////////
  33. public static void CalledOnUnityMainThread()
  34. {
  35. while (onResultQueue.Count > 0)
  36. {
  37. onResultQueue.Dequeue().Invoke();
  38. }
  39. }
  40.  
  41. public void Run( ThreadCall threadCall, object data, Action onResult )
  42. {
  43. var thread = new Thread(ThreadFunction);
  44. ThreadParams threadParams = new ThreadParams(threadCall, data, onResult);
  45. thread.Start(threadParams);
  46. thread.IsBackground = true;
  47. }
  48.  
  49. ////////////////////////////////////////////////////////////////////////////////////////////////////
  50. //Private methods
  51. ////////////////////////////////////////////////////////////////////////////////////////////////////
  52. private static void ThreadFunction( object state )
  53. {
  54. ThreadParams threadParams;
  55. try
  56. {
  57. threadParams = (ThreadParams) state;
  58. }
  59. catch
  60. {
  61. return;
  62. }
  63.  
  64. threadParams.threadCall( threadParams.data, threadParams.onResult );
  65.  
  66. lock(lockObj)
  67. {
  68. onResultQueue.Enqueue(threadParams.onResult);
  69. }
  70. }
  71.  
  72. ////////////////////////////////////////////////////////////////////////////////////////////////////
  73. //Private fields
  74. ////////////////////////////////////////////////////////////////////////////////////////////////////
  75. private static Queue<Action> onResultQueue = new Queue<Action>();
  76. private static System.Object lockObj = new System.Object();
  77. }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement