ConnectionBufferPool.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.Runtime;
  7. class ConnectionBufferPool : QueuedObjectPool<byte[]>
  8. {
  9. const int SingleBatchSize = 128 * 1024;
  10. const int MaxBatchCount = 16;
  11. const int MaxFreeCountFactor = 4;
  12. int bufferSize;
  13. public ConnectionBufferPool(int bufferSize)
  14. {
  15. int batchCount = ComputeBatchCount(bufferSize);
  16. this.Initialize(bufferSize, batchCount, batchCount * MaxFreeCountFactor);
  17. }
  18. public ConnectionBufferPool(int bufferSize, int maxFreeCount)
  19. {
  20. this.Initialize(bufferSize, ComputeBatchCount(bufferSize), maxFreeCount);
  21. }
  22. void Initialize(int bufferSize, int batchCount, int maxFreeCount)
  23. {
  24. Fx.Assert(bufferSize >= 0, "bufferSize must be non-negative");
  25. Fx.Assert(batchCount > 0, "batchCount must be positive");
  26. Fx.Assert(maxFreeCount >= 0, "maxFreeCount must be non-negative");
  27. this.bufferSize = bufferSize;
  28. if (maxFreeCount < batchCount)
  29. {
  30. maxFreeCount = batchCount;
  31. }
  32. base.Initialize(batchCount, maxFreeCount);
  33. }
  34. public int BufferSize
  35. {
  36. get
  37. {
  38. return this.bufferSize;
  39. }
  40. }
  41. protected override byte[] Create()
  42. {
  43. return DiagnosticUtility.Utility.AllocateByteArray(this.bufferSize);
  44. }
  45. static int ComputeBatchCount(int bufferSize)
  46. {
  47. int batchCount;
  48. if (bufferSize != 0)
  49. {
  50. batchCount = (SingleBatchSize + bufferSize - 1) / bufferSize;
  51. if (batchCount > MaxBatchCount)
  52. {
  53. batchCount = MaxBatchCount;
  54. }
  55. }
  56. else
  57. {
  58. // It's OK to have zero bufferSize
  59. batchCount = MaxBatchCount;
  60. }
  61. return batchCount;
  62. }
  63. }
  64. }