diff --git a/src/System.ServiceModel.NetFramingBase/src/System/ServiceModel/Channels/TransportDuplexSessionChannel.cs b/src/System.ServiceModel.NetFramingBase/src/System/ServiceModel/Channels/TransportDuplexSessionChannel.cs index e7c88e3e729..9af3fa44609 100644 --- a/src/System.ServiceModel.NetFramingBase/src/System/ServiceModel/Channels/TransportDuplexSessionChannel.cs +++ b/src/System.ServiceModel.NetFramingBase/src/System/ServiceModel/Channels/TransportDuplexSessionChannel.cs @@ -17,6 +17,7 @@ internal abstract class TransportDuplexSessionChannel : TransportOutputChannel, { private bool _isInputSessionClosed; private bool _isOutputSessionClosed; + private bool _releasingConnection; private Uri _localVia; private ChannelBinding _channelBindingToken; @@ -290,6 +291,11 @@ protected async Task CloseOutputSessionAsync(TimeSpan timeout) protected override void OnAbort() { + if (_releasingConnection) + { + // We are releasing the connection to the pool. + return; + } ReturnConnectionIfNecessary(true, TimeSpan.Zero); } @@ -567,6 +573,9 @@ private void OnOutputSessionClosed(ref TimeoutHelper timeoutHelper) if (releaseConnection) { + // Call Abort() to ensure proper channel state before returning the connection to the pool. + _releasingConnection = true; + Abort(); ReturnConnectionIfNecessary(false, timeoutHelper.RemainingTime()); } } diff --git a/src/System.ServiceModel.Primitives/src/System/ServiceModel/Channels/ServiceChannel.cs b/src/System.ServiceModel.Primitives/src/System/ServiceModel/Channels/ServiceChannel.cs index c38be4de023..aed773f7be3 100644 --- a/src/System.ServiceModel.Primitives/src/System/ServiceModel/Channels/ServiceChannel.cs +++ b/src/System.ServiceModel.Primitives/src/System/ServiceModel/Channels/ServiceChannel.cs @@ -374,6 +374,7 @@ private void SetupInnerChannelFaultHandler() // NullReferenceException in this method or in the OnInnerChannelFaulted method; // because this method accesses this.binder and OnInnerChannelFaulted accesses this.clientRuntime. Binder.Channel.Faulted += OnInnerChannelFaulted; + Binder.Channel.Closed += OnInnerChannelClosed; } private void BindDuplexCallbacks() @@ -1169,6 +1170,16 @@ private void OnInnerChannelFaulted(object sender, EventArgs e) } } + private void OnInnerChannelClosed(object sender, EventArgs e) + { + if (HasSession) + { + DispatchRuntime dispatchRuntime = ClientRuntime.DispatchRuntime; + } + + Abort(); + } + private void AddMessageProperties(Message message, OperationContext context) { if (_allowOutputBatching)