Actor.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using Common.Base;
  5. using Common.Logger;
  6. using MongoDB.Bson;
  7. namespace Model
  8. {
  9. public class Actor : Entity<Unit>, IDisposable
  10. {
  11. private readonly Queue<Env> msgEnvQueue = new Queue<Env>();
  12. private Action msgAction = () => { };
  13. private Env Env { get; set; }
  14. private bool isStop;
  15. public Actor(ObjectId id): base(id)
  16. {
  17. this.Start();
  18. }
  19. private async void Start()
  20. {
  21. while (!this.isStop)
  22. {
  23. try
  24. {
  25. Env env = await this.Get();
  26. this.Env = env;
  27. ushort opcode = env.Get<ushort>(EnvKey.Opcode);
  28. await World.Instance.GetComponent<MessageComponent>().RunAsync(opcode, env);
  29. }
  30. catch (Exception e)
  31. {
  32. Log.Trace(string.Format(e.ToString()));
  33. }
  34. }
  35. }
  36. public void Add(Env msgEnv)
  37. {
  38. this.msgEnvQueue.Enqueue(msgEnv);
  39. this.msgAction();
  40. }
  41. private Task<Env> Get()
  42. {
  43. var tcs = new TaskCompletionSource<Env>();
  44. if (this.msgEnvQueue.Count > 0)
  45. {
  46. Env env = this.msgEnvQueue.Dequeue();
  47. tcs.SetResult(env);
  48. }
  49. else
  50. {
  51. this.msgAction = () =>
  52. {
  53. this.msgAction = () => { };
  54. Env msg = this.msgEnvQueue.Dequeue();
  55. tcs.SetResult(msg);
  56. };
  57. }
  58. return tcs.Task;
  59. }
  60. public void Dispose()
  61. {
  62. this.isStop = true;
  63. }
  64. }
  65. }