TPoller.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System.Collections.Concurrent;
  2. using System.Collections.Generic;
  3. namespace TNet
  4. {
  5. public class TPoller
  6. {
  7. private readonly BlockingCollection<TSocketState> blockingCollection = new BlockingCollection<TSocketState>();
  8. public HashSet<TSocket> CanWriteSocket = new HashSet<TSocket>();
  9. public void Add(TSocketState tSocketState)
  10. {
  11. this.blockingCollection.Add(tSocketState);
  12. }
  13. public void Dispose()
  14. {
  15. }
  16. public void RunOnce(int timeout)
  17. {
  18. foreach (TSocket socket in CanWriteSocket)
  19. {
  20. if (socket.IsSending)
  21. {
  22. continue;
  23. }
  24. socket.BeginSend();
  25. }
  26. this.CanWriteSocket.Clear();
  27. TSocketState socketState;
  28. if (!this.blockingCollection.TryTake(out socketState, timeout))
  29. {
  30. return;
  31. }
  32. var stateQueue = new Queue<TSocketState>();
  33. stateQueue.Enqueue(socketState);
  34. while (true)
  35. {
  36. if (!this.blockingCollection.TryTake(out socketState, 0))
  37. {
  38. break;
  39. }
  40. stateQueue.Enqueue(socketState);
  41. }
  42. while (stateQueue.Count > 0)
  43. {
  44. TSocketState state = stateQueue.Dequeue();
  45. state.Run();
  46. }
  47. }
  48. public void Run()
  49. {
  50. while (true)
  51. {
  52. this.RunOnce(1);
  53. }
  54. }
  55. }
  56. }