ActorComponent.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using Common.Base;
  5. using Common.Event;
  6. using Common.Logger;
  7. namespace Model
  8. {
  9. public class ActorComponent : Component<Unit>
  10. {
  11. private readonly Queue<Env> msgEnvQueue = new Queue<Env>();
  12. private Action msgAction = () => {};
  13. private Env Env { get; set; }
  14. public ActorComponent()
  15. {
  16. Start();
  17. }
  18. private async void Start()
  19. {
  20. while (true)
  21. {
  22. try
  23. {
  24. Env env = await this.Get();
  25. this.Env = env;
  26. var message = env.Get<byte[]>(EnvKey.Message);
  27. int opcode = BitConverter.ToUInt16(message, 0);
  28. await World.Instance.GetComponent<EventComponent<MessageAttribute>>().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. 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. msgAction = () =>
  52. {
  53. msgAction = () => { };
  54. Env msg = this.msgEnvQueue.Dequeue();
  55. tcs.SetResult(msg);
  56. };
  57. }
  58. return tcs.Task;
  59. }
  60. }
  61. }