ChannelPool.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. //------------------------------------------------------------
  2. // Copyright (c) Microsoft Corporation. All rights reserved.
  3. //------------------------------------------------------------
  4. namespace System.ServiceModel.Channels
  5. {
  6. using System.Diagnostics;
  7. using System.Runtime;
  8. using System.ServiceModel;
  9. // Pool of channels used by OneWayChannelFactories
  10. class ChannelPool<TChannel> : IdlingCommunicationPool<ChannelPoolKey, TChannel>
  11. where TChannel : class, IChannel
  12. {
  13. static AsyncCallback onCloseComplete = Fx.ThunkCallback(new AsyncCallback(OnCloseComplete));
  14. public ChannelPool(ChannelPoolSettings settings)
  15. : base(settings.MaxOutboundChannelsPerEndpoint, settings.IdleTimeout, settings.LeaseTimeout)
  16. {
  17. }
  18. protected override void AbortItem(TChannel item)
  19. {
  20. item.Abort();
  21. }
  22. protected override void CloseItem(TChannel item, TimeSpan timeout)
  23. {
  24. item.Close(timeout);
  25. }
  26. protected override void CloseItemAsync(TChannel item, TimeSpan timeout)
  27. {
  28. bool succeeded = false;
  29. try
  30. {
  31. IAsyncResult result = item.BeginClose(timeout, onCloseComplete, item);
  32. if (result.CompletedSynchronously)
  33. {
  34. item.EndClose(result);
  35. }
  36. succeeded = true;
  37. }
  38. finally
  39. {
  40. if (!succeeded)
  41. {
  42. item.Abort();
  43. }
  44. }
  45. }
  46. protected override ChannelPoolKey GetPoolKey(EndpointAddress address, Uri via)
  47. {
  48. return new ChannelPoolKey(address, via);
  49. }
  50. static void OnCloseComplete(IAsyncResult result)
  51. {
  52. if (result.CompletedSynchronously)
  53. {
  54. return;
  55. }
  56. TChannel item = (TChannel)result.AsyncState;
  57. bool succeeded = false;
  58. try
  59. {
  60. item.EndClose(result);
  61. succeeded = true;
  62. }
  63. catch (Exception e)
  64. {
  65. if (Fx.IsFatal(e))
  66. {
  67. throw;
  68. }
  69. DiagnosticUtility.TraceHandledException(e, TraceEventType.Warning);
  70. }
  71. finally
  72. {
  73. if (!succeeded)
  74. {
  75. item.Abort();
  76. }
  77. }
  78. }
  79. }
  80. class ChannelPoolKey : IEquatable<ChannelPoolKey>
  81. {
  82. EndpointAddress address;
  83. Uri via;
  84. public ChannelPoolKey(EndpointAddress address, Uri via)
  85. {
  86. this.address = address;
  87. this.via = via;
  88. }
  89. public override int GetHashCode()
  90. {
  91. return address.GetHashCode() + via.GetHashCode();
  92. }
  93. public bool Equals(ChannelPoolKey other)
  94. {
  95. return address.EndpointEquals(other.address) && via.Equals(other.via);
  96. }
  97. }
  98. }