ActorComponent.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. public Action msgAction = () => {};
  13. public Env Env { get; private set; }
  14. public async void Run()
  15. {
  16. while (true)
  17. {
  18. try
  19. {
  20. Env env = await this.Get();
  21. this.Env = env;
  22. var message = env.Get<byte[]>(EnvKey.Message);
  23. int opcode = BitConverter.ToUInt16(message, 0);
  24. await World.Instance.GetComponent<EventComponent<MessageAttribute>>().RunAsync(opcode, env);
  25. }
  26. catch (Exception e)
  27. {
  28. Log.Trace(string.Format(e.ToString()));
  29. }
  30. }
  31. }
  32. public void Add(Env msgEnv)
  33. {
  34. this.msgEnvQueue.Enqueue(msgEnv);
  35. msgAction();
  36. }
  37. private Task<Env> Get()
  38. {
  39. var tcs = new TaskCompletionSource<Env>();
  40. if (this.msgEnvQueue.Count > 0)
  41. {
  42. Env env = this.msgEnvQueue.Dequeue();
  43. tcs.SetResult(env);
  44. }
  45. else
  46. {
  47. msgAction = () =>
  48. {
  49. msgAction = () => { };
  50. Env msg = this.msgEnvQueue.Dequeue();
  51. tcs.SetResult(msg);
  52. };
  53. }
  54. return tcs.Task;
  55. }
  56. }
  57. }