SocketAsyncEventArgsPool.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.Diagnostics;
  7. using System.Net.Sockets;
  8. using System.Runtime;
  9. class SocketAsyncEventArgsPool : QueuedObjectPool<SocketAsyncEventArgs>
  10. {
  11. const int SingleBatchSize = 128 * 1024;
  12. const int MaxBatchCount = 16;
  13. const int MaxFreeCountFactor = 4;
  14. int acceptBufferSize;
  15. public SocketAsyncEventArgsPool(int acceptBufferSize)
  16. {
  17. if (acceptBufferSize <= 0)
  18. {
  19. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("acceptBufferSize"));
  20. }
  21. this.acceptBufferSize = acceptBufferSize;
  22. int batchCount = (SingleBatchSize + acceptBufferSize - 1) / acceptBufferSize;
  23. if (batchCount > MaxBatchCount)
  24. {
  25. batchCount = MaxBatchCount;
  26. }
  27. Initialize(batchCount, batchCount * MaxFreeCountFactor);
  28. }
  29. public override bool Return(SocketAsyncEventArgs socketAsyncEventArgs)
  30. {
  31. CleanupAcceptSocket(socketAsyncEventArgs);
  32. if (!base.Return(socketAsyncEventArgs))
  33. {
  34. this.CleanupItem(socketAsyncEventArgs);
  35. return false;
  36. }
  37. return true;
  38. }
  39. internal static void CleanupAcceptSocket(SocketAsyncEventArgs socketAsyncEventArgs)
  40. {
  41. Fx.Assert(socketAsyncEventArgs != null, "socketAsyncEventArgs should not be null.");
  42. Socket socket = socketAsyncEventArgs.AcceptSocket;
  43. if (socket != null)
  44. {
  45. socketAsyncEventArgs.AcceptSocket = null;
  46. try
  47. {
  48. socket.Close(0);
  49. }
  50. catch (SocketException ex)
  51. {
  52. FxTrace.Exception.TraceHandledException(ex, TraceEventType.Information);
  53. }
  54. catch (ObjectDisposedException ex)
  55. {
  56. FxTrace.Exception.TraceHandledException(ex, TraceEventType.Information);
  57. }
  58. }
  59. }
  60. protected override void CleanupItem(SocketAsyncEventArgs item)
  61. {
  62. item.Dispose();
  63. }
  64. protected override SocketAsyncEventArgs Create()
  65. {
  66. SocketAsyncEventArgs eventArgs = new SocketAsyncEventArgs();
  67. byte[] acceptBuffer = DiagnosticUtility.Utility.AllocateByteArray(this.acceptBufferSize);
  68. eventArgs.SetBuffer(acceptBuffer, 0, this.acceptBufferSize);
  69. return eventArgs;
  70. }
  71. }
  72. }