SocketTokenManager.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. namespace IFramework.Net
  5. {
  6. internal class SocketTokenManager<T>
  7. {
  8. private Queue<T> collection = null;
  9. private LockParam lockParam = new LockParam();
  10. private int capacity = 4;
  11. public int Count
  12. {
  13. get { return collection.Count; }
  14. }
  15. public int Capacity { get { return capacity; } }
  16. public SocketTokenManager(int capacity = 32)
  17. {
  18. this.capacity = capacity;
  19. collection = new Queue<T>(capacity);
  20. }
  21. public T Get()
  22. {
  23. using (LockWait lwait = new LockWait(ref lockParam))
  24. {
  25. if (collection.Count > 0)
  26. return collection.Dequeue();
  27. else return default(T);
  28. }
  29. }
  30. public void Set(T item)
  31. {
  32. using (LockWait lwait = new LockWait(ref lockParam))
  33. {
  34. collection.Enqueue(item);
  35. }
  36. }
  37. public void Clear()
  38. {
  39. using (LockWait lwait = new LockWait(ref lockParam))
  40. {
  41. collection.Clear();
  42. }
  43. }
  44. public void ClearToCloseToken()
  45. {
  46. using (LockWait lwait = new LockWait(ref lockParam))
  47. {
  48. while (collection.Count > 0)
  49. {
  50. var token = collection.Dequeue() as SocketToken;
  51. if (token != null) token.Close();
  52. }
  53. }
  54. }
  55. public void ClearToCloseArgs()
  56. {
  57. using (LockWait lwait = new LockWait(ref lockParam))
  58. {
  59. while (collection.Count > 0)
  60. {
  61. var token = collection.Dequeue() as System.Net.Sockets.SocketAsyncEventArgs;
  62. if (token != null)
  63. {
  64. token.Dispose();
  65. }
  66. }
  67. }
  68. }
  69. public T GetEmptyWait(Func<int, bool> fun, bool isWaitingFor = false)
  70. {
  71. int retry = 1;
  72. while (true)
  73. {
  74. var tArgs = Get();
  75. if (tArgs != null) return tArgs;
  76. if (isWaitingFor == false)
  77. {
  78. if (retry > 16) break;
  79. ++retry;
  80. }
  81. var isContinue = fun(retry);
  82. if (isContinue == false) break;
  83. Thread.Sleep(1000 * retry);
  84. }
  85. return default(T);
  86. }
  87. }
  88. }