ActorComponent.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using Common.Base;
  5. using Common.Logger;
  6. namespace Model
  7. {
  8. public class ActorComponent: Component<Unit>
  9. {
  10. private readonly Queue<Env> msgEnvQueue = new Queue<Env>();
  11. private Action msgAction = () => { };
  12. private Env Env { get; set; }
  13. public ActorComponent()
  14. {
  15. this.Start();
  16. }
  17. private async void Start()
  18. {
  19. while (true)
  20. {
  21. try
  22. {
  23. Env env = await this.Get();
  24. this.Env = env;
  25. var message = env.Get<byte[]>(EnvKey.Message);
  26. int opcode = BitConverter.ToUInt16(message, 0);
  27. await World.Instance.GetComponent<EventComponent<MessageAttribute>>().RunAsync(opcode, env);
  28. }
  29. catch (Exception e)
  30. {
  31. Log.Trace(string.Format(e.ToString()));
  32. }
  33. }
  34. }
  35. public void Add(Env msgEnv)
  36. {
  37. this.msgEnvQueue.Enqueue(msgEnv);
  38. this.msgAction();
  39. }
  40. private Task<Env> Get()
  41. {
  42. var tcs = new TaskCompletionSource<Env>();
  43. if (this.msgEnvQueue.Count > 0)
  44. {
  45. Env env = this.msgEnvQueue.Dequeue();
  46. tcs.SetResult(env);
  47. }
  48. else
  49. {
  50. this.msgAction = () =>
  51. {
  52. this.msgAction = () => { };
  53. Env msg = this.msgEnvQueue.Dequeue();
  54. tcs.SetResult(msg);
  55. };
  56. }
  57. return tcs.Task;
  58. }
  59. }
  60. }