Buff.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. using System;
  2. using Common.Base;
  3. using Common.Helper;
  4. using MongoDB.Bson;
  5. using MongoDB.Bson.Serialization.Attributes;
  6. namespace Model
  7. {
  8. public class Buff: Entity<Buff>, IDisposable
  9. {
  10. [BsonElement]
  11. private int configId { get; set; }
  12. [BsonElement]
  13. private ObjectId ownerId;
  14. [BsonElement]
  15. private long expiration;
  16. [BsonIgnore]
  17. private ObjectId timerId;
  18. [BsonIgnore]
  19. public long Expiration
  20. {
  21. get
  22. {
  23. return this.expiration;
  24. }
  25. set
  26. {
  27. this.expiration = value;
  28. }
  29. }
  30. [BsonIgnore]
  31. public ObjectId TimerId
  32. {
  33. get
  34. {
  35. return this.timerId;
  36. }
  37. set
  38. {
  39. this.timerId = value;
  40. }
  41. }
  42. public Buff(int configId, ObjectId ownerId)
  43. {
  44. this.configId = configId;
  45. this.ownerId = ownerId;
  46. if (this.Config.Duration != 0)
  47. {
  48. this.Expiration = TimeHelper.Now() + this.Config.Duration;
  49. }
  50. if (this.Expiration != 0)
  51. {
  52. // 注册Timer回调
  53. Env env = new Env();
  54. env[EnvKey.OwnerId] = this.OwnerId;
  55. env[EnvKey.BuffId] = this.Id;
  56. this.TimerId = World.Instance.GetComponent<TimerComponent>()
  57. .Add(this.Expiration, EventType.BuffTimeoutAction, env);
  58. }
  59. }
  60. protected void Dispose(bool disposing)
  61. {
  62. if (this.Expiration == 0)
  63. {
  64. return;
  65. }
  66. // Buff在垃圾回收或者主动Dispose,都需要释放Timer回调.非托管资源
  67. World.Instance.GetComponent<TimerComponent>().Remove(this.TimerId);
  68. this.expiration = 0;
  69. }
  70. ~Buff()
  71. {
  72. this.Dispose(false);
  73. }
  74. public void Dispose()
  75. {
  76. this.Dispose(true);
  77. }
  78. public override void EndInit()
  79. {
  80. base.EndInit();
  81. if (this.Expiration != 0)
  82. {
  83. // 注册Timer回调
  84. Env env = new Env();
  85. env[EnvKey.OwnerId] = this.OwnerId;
  86. env[EnvKey.BuffId] = this.Id;
  87. this.TimerId = World.Instance.GetComponent<TimerComponent>()
  88. .Add(this.Expiration, EventType.BuffTimeoutAction, env);
  89. }
  90. }
  91. [BsonIgnore]
  92. public BuffConfig Config
  93. {
  94. get
  95. {
  96. return World.Instance.GetComponent<ConfigComponent>().Get<BuffConfig>(this.configId);
  97. }
  98. }
  99. [BsonIgnore]
  100. public ObjectId OwnerId
  101. {
  102. get
  103. {
  104. return this.ownerId;
  105. }
  106. set
  107. {
  108. this.ownerId = value;
  109. }
  110. }
  111. }
  112. }