Buff.cs 2.3 KB

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