TPoller.cs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. namespace TNet
  5. {
  6. public class TPoller
  7. {
  8. // 线程同步队列,发送接收socket回调都放到该队列,由poll线程统一执行
  9. private readonly BlockingCollection<Action> blockingCollection = new BlockingCollection<Action>();
  10. public void Add(Action action)
  11. {
  12. this.blockingCollection.Add(action);
  13. }
  14. public void Dispose()
  15. {
  16. }
  17. public void RunOnce(int timeout)
  18. {
  19. // 处理读写线程的回调
  20. Action action;
  21. if (!this.blockingCollection.TryTake(out action, timeout))
  22. {
  23. return;
  24. }
  25. var queue = new Queue<Action>();
  26. queue.Enqueue(action);
  27. while (true)
  28. {
  29. if (!this.blockingCollection.TryTake(out action, 0))
  30. {
  31. break;
  32. }
  33. queue.Enqueue(action);
  34. }
  35. while (queue.Count > 0)
  36. {
  37. Action a = queue.Dequeue();
  38. a();
  39. }
  40. }
  41. public void Run()
  42. {
  43. while (true)
  44. {
  45. this.RunOnce(10);
  46. }
  47. }
  48. }
  49. }