TPoller.cs 923 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. namespace TNet
  5. {
  6. public class TPoller : IPoller
  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 Run(int timeout)
  15. {
  16. // 处理读写线程的回调
  17. Action action;
  18. if (this.blockingCollection.TryTake(out action, timeout))
  19. {
  20. var queue = new Queue<Action>();
  21. queue.Enqueue(action);
  22. while (true)
  23. {
  24. if (!this.blockingCollection.TryTake(out action, 0))
  25. {
  26. break;
  27. }
  28. queue.Enqueue(action);
  29. }
  30. while (queue.Count > 0)
  31. {
  32. Action a = queue.Dequeue();
  33. a();
  34. }
  35. }
  36. }
  37. }
  38. }