Actor.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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<byte[]> msgQueue = new Queue<byte[]>();
  12. private Action msgAction = () => { };
  13. private bool isStop;
  14. public Actor(ObjectId id): base(id)
  15. {
  16. this.Start();
  17. }
  18. private async void Start()
  19. {
  20. while (!this.isStop)
  21. {
  22. try
  23. {
  24. byte[] messageBytes = await this.Get();
  25. Opcode opcode = (Opcode)BitConverter.ToUInt16(messageBytes, 0);
  26. await World.Instance.GetComponent<MessageComponent>().RunAsync(opcode, messageBytes);
  27. }
  28. catch (Exception e)
  29. {
  30. Log.Trace(e.ToString());
  31. }
  32. }
  33. }
  34. public void Add(byte[] msg)
  35. {
  36. this.msgQueue.Enqueue(msg);
  37. this.msgAction();
  38. }
  39. private Task<byte[]> Get()
  40. {
  41. var tcs = new TaskCompletionSource<byte[]>();
  42. if (this.msgQueue.Count > 0)
  43. {
  44. byte[] messageBytes = this.msgQueue.Dequeue();
  45. tcs.SetResult(messageBytes);
  46. }
  47. else
  48. {
  49. this.msgAction = () =>
  50. {
  51. this.msgAction = () => { };
  52. byte[] msg = this.msgQueue.Dequeue();
  53. tcs.SetResult(msg);
  54. };
  55. }
  56. return tcs.Task;
  57. }
  58. public void Dispose()
  59. {
  60. this.isStop = true;
  61. }
  62. }
  63. }