TPoller.cs 790 B

1234567891011121314151617181920212223242526272829303132333435363738
  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 ConcurrentQueue<Action> concurrentQueue = new ConcurrentQueue<Action>();
  10. private readonly Queue<Action> localQueue = new Queue<Action>();
  11. public void Add(Action action)
  12. {
  13. this.concurrentQueue.Enqueue(action);
  14. }
  15. public void Run()
  16. {
  17. while (true)
  18. {
  19. Action action;
  20. if (!this.concurrentQueue.TryDequeue(out action))
  21. {
  22. break;
  23. }
  24. localQueue.Enqueue(action);
  25. }
  26. while (localQueue.Count > 0)
  27. {
  28. Action a = localQueue.Dequeue();
  29. a();
  30. }
  31. }
  32. }
  33. }