ActorComponent.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using Common.Base;
  5. using Common.Event;
  6. namespace Model
  7. {
  8. public class ActorComponent : Component<Unit>
  9. {
  10. private readonly Queue<Env> msgEnvQueue = new Queue<Env>();
  11. public Action msgAction = () => {};
  12. public async void Run()
  13. {
  14. while (true)
  15. {
  16. Env env = await this.Get();
  17. var message = env.Get<byte[]>(EnvKey.Message);
  18. int opcode = BitConverter.ToUInt16(message, 0);
  19. await World.Instance.GetComponent<EventComponent<MessageAttribute>>().Run(opcode, env);
  20. }
  21. }
  22. public void Add(Env msgEnv)
  23. {
  24. this.msgEnvQueue.Enqueue(msgEnv);
  25. msgAction();
  26. }
  27. private Task<Env> Get()
  28. {
  29. var tcs = new TaskCompletionSource<Env>();
  30. if (this.msgEnvQueue.Count > 0)
  31. {
  32. Env env = this.msgEnvQueue.Dequeue();
  33. tcs.SetResult(env);
  34. }
  35. else
  36. {
  37. msgAction = () =>
  38. {
  39. msgAction = () => { };
  40. Env msg = this.msgEnvQueue.Dequeue();
  41. tcs.SetResult(msg);
  42. };
  43. }
  44. return tcs.Task;
  45. }
  46. }
  47. }