AnimationQueue.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Threading;
  4. using System.Threading.Tasks;
  5. namespace MECF.Framework.UI.Client.ClientControls.Common
  6. {
  7. public class AnimationQueue
  8. {
  9. private ConcurrentQueue<AnimationParameter> queue;
  10. private AutoResetEvent eventHandler;
  11. public event EventHandler<StatusUpdateArgs> StatusUpdated;
  12. private bool idle;
  13. private ReaderWriterLockSlim idleLocker;
  14. private readonly string name;
  15. public AnimationQueue(string name)
  16. {
  17. idleLocker = new ReaderWriterLockSlim();
  18. eventHandler = new AutoResetEvent(false);
  19. queue = new ConcurrentQueue<AnimationParameter>();
  20. idle = true;
  21. this.name = name;
  22. Task.Run(() => Consume());
  23. }
  24. public void EnqueueStatus(AnimationParameter parameter)
  25. {
  26. queue.Enqueue(parameter);
  27. try
  28. {
  29. idleLocker.EnterReadLock();
  30. if (idle)
  31. {
  32. eventHandler.Set();
  33. idle = false;
  34. }
  35. }
  36. finally
  37. {
  38. idleLocker.ExitReadLock();
  39. }
  40. }
  41. public AnimationParameter LastStatus
  42. {
  43. get;
  44. private set;
  45. }
  46. private void Consume()
  47. {
  48. Thread.CurrentThread.Name = name;
  49. while (true)
  50. {
  51. eventHandler.WaitOne();
  52. AnimationParameter parameter = null;
  53. if (queue.TryDequeue(out parameter))
  54. {
  55. LastStatus = parameter;
  56. if (StatusUpdated != null)
  57. {
  58. try
  59. {
  60. idleLocker.EnterWriteLock();
  61. idle = false;
  62. }
  63. finally
  64. {
  65. idleLocker.ExitWriteLock();
  66. }
  67. StatusUpdated(this, new StatusUpdateArgs() { Event = eventHandler, Parameter = parameter });
  68. }
  69. }
  70. else
  71. {
  72. try
  73. {
  74. idleLocker.EnterWriteLock();
  75. idle = true;
  76. }
  77. finally
  78. {
  79. idleLocker.ExitWriteLock();
  80. }
  81. }
  82. }
  83. }
  84. }
  85. public class StatusUpdateArgs : EventArgs
  86. {
  87. public AutoResetEvent Event { get; set; }
  88. public AnimationParameter Parameter { get; set; }
  89. }
  90. public class AnimationParameter
  91. {
  92. public string Target { get; set; }
  93. public string ArmA { get; set; }
  94. public string ArmB { get; set; }
  95. }
  96. }