NetThread.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA_8_1
  2. #if WINRT && !UNITY_EDITOR
  3. #define USE_WINRT
  4. #endif
  5. using System;
  6. using System.Threading;
  7. #if USE_WINRT
  8. using Windows.Foundation;
  9. using Windows.System.Threading;
  10. using Windows.System.Threading.Core;
  11. #endif
  12. namespace FlyingWormConsole3.LiteNetLib
  13. {
  14. public sealed class NetThread
  15. {
  16. #if USE_WINRT
  17. private readonly ManualResetEvent _updateWaiter = new ManualResetEvent(false);
  18. private readonly ManualResetEvent _joinWaiter = new ManualResetEvent(false);
  19. #else
  20. private Thread _thread;
  21. #endif
  22. private readonly Action _callback;
  23. public int SleepTime;
  24. private bool _running;
  25. private readonly string _name;
  26. public bool IsRunning
  27. {
  28. get { return _running; }
  29. }
  30. public NetThread(string name, int sleepTime, Action callback)
  31. {
  32. _callback = callback;
  33. SleepTime = sleepTime;
  34. _name = name;
  35. }
  36. public void Start()
  37. {
  38. if (_running)
  39. return;
  40. _running = true;
  41. #if USE_WINRT
  42. var thread = new PreallocatedWorkItem(ThreadLogic, WorkItemPriority.Normal, WorkItemOptions.TimeSliced);
  43. thread.RunAsync().AsTask();
  44. #else
  45. _thread = new Thread(ThreadLogic)
  46. {
  47. Name = _name,
  48. IsBackground = true
  49. };
  50. _thread.Start();
  51. #endif
  52. }
  53. public void Stop()
  54. {
  55. if (!_running)
  56. return;
  57. _running = false;
  58. #if USE_WINRT
  59. _joinWaiter.WaitOne();
  60. #else
  61. _thread.Join();
  62. #endif
  63. }
  64. #if USE_WINRT
  65. private void ThreadLogic(IAsyncAction action)
  66. {
  67. while (_running)
  68. {
  69. _callback();
  70. _updateWaiter.WaitOne(SleepTime);
  71. }
  72. _joinWaiter.Set();
  73. }
  74. #else
  75. private void ThreadLogic()
  76. {
  77. while (_running)
  78. {
  79. _callback();
  80. Thread.Sleep(SleepTime);
  81. }
  82. }
  83. #endif
  84. }
  85. }
  86. #endif