TimerComponent.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System.Collections.Generic;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Common.Base;
  5. using Common.Helper;
  6. using MongoDB.Bson;
  7. namespace Model
  8. {
  9. public class TimerComponent: Component<World>, IUpdate
  10. {
  11. private class Timer
  12. {
  13. public ObjectId Id { get; set; }
  14. public long Time { get; set; }
  15. public EventType CallbackEvent { get; set; }
  16. public Env Env { get; set; }
  17. }
  18. private readonly Dictionary<ObjectId, Timer> timers = new Dictionary<ObjectId, Timer>();
  19. /// <summary>
  20. /// key: time, value: timer id
  21. /// </summary>
  22. private readonly MultiMap<long, ObjectId> timeId = new MultiMap<long, ObjectId>();
  23. public ObjectId Add(long time, EventType callbackEvent, Env env)
  24. {
  25. Timer timer = new Timer
  26. {
  27. Id = ObjectId.GenerateNewId(),
  28. Time = time,
  29. CallbackEvent = callbackEvent,
  30. Env = env
  31. };
  32. this.timers[timer.Id] = timer;
  33. this.timeId.Add(timer.Time, timer.Id);
  34. return timer.Id;
  35. }
  36. public void Remove(ObjectId id)
  37. {
  38. Timer timer;
  39. if (!this.timers.TryGetValue(id, out timer))
  40. {
  41. return;
  42. }
  43. this.timeId.Remove(timer.Time, timer.Id);
  44. }
  45. public Task<bool> Sleep(int time)
  46. {
  47. TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
  48. Env env = new Env();
  49. env[EnvKey.SleepTimeout_TaskCompletionSource] = tcs;
  50. this.Add(TimeHelper.Now() + time, EventType.SleepTimeout, env);
  51. return tcs.Task;
  52. }
  53. public void Update()
  54. {
  55. long timeNow = TimeHelper.Now();
  56. while (true)
  57. {
  58. KeyValuePair<long, List<ObjectId>> first = this.timeId.First;
  59. if (first.Key > timeNow)
  60. {
  61. return;
  62. }
  63. List<ObjectId> timeoutId = first.Value;
  64. this.timeId.Remove(first.Key);
  65. foreach (ObjectId id in timeoutId)
  66. {
  67. Timer timer;
  68. if (!this.timers.TryGetValue(id, out timer))
  69. {
  70. continue;
  71. }
  72. this.timers.Remove(id);
  73. World.Instance.GetComponent<EventComponent<EventAttribute>>().RunAsync(timer.CallbackEvent, timer.Env);
  74. }
  75. }
  76. }
  77. }
  78. }