From e58ebfa6b4cf967880f12e378de7176dcf616187 Mon Sep 17 00:00:00 2001 From: Paul Higinbotham Date: Fri, 20 Dec 2019 13:20:10 -0800 Subject: [PATCH] Fix race condition exception on recent change to OutOfProc transport (#11406) --- .../fanin/OutOfProcTransportManager.cs | 50 ++++++++++++++----- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index c94f5a7461..baef84419a 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -628,7 +628,29 @@ namespace System.Management.Automation.Remoting.Client { _cmdTransportManagers.Clear(); _closeTimeOutTimer.Dispose(); + + // Stop session processing thread. + try + { + _sessionMessageQueue.CompleteAdding(); + } + catch (ObjectDisposedException) + { + // Object already disposed. + } + _sessionMessageQueue.Dispose(); + + // Stop command processing thread. + try + { + _commandMessageQueue.CompleteAdding(); + } + catch (ObjectDisposedException) + { + // Object already disposed. + } + _commandMessageQueue.Dispose(); } } @@ -683,10 +705,6 @@ namespace System.Management.Automation.Remoting.Client // stop timer _closeTimeOutTimer.Change(Timeout.Infinite, Timeout.Infinite); - // Stop protocol message processing threads. - _sessionMessageQueue.CompleteAdding(); - _commandMessageQueue.CompleteAdding(); - RaiseCloseCompleted(); CleanupConnection(); } @@ -753,17 +771,25 @@ namespace System.Management.Automation.Remoting.Client protected void HandleOutputDataReceived(string data) { - // Route protocol message based on whether it is a session or command message. - // Session messages have empty Guid values. - if (Guid.Equals(GetMessageGuid(data), Guid.Empty)) + try { - // Session message - _sessionMessageQueue.Add(data); + // Route protocol message based on whether it is a session or command message. + // Session messages have empty Guid values. + if (Guid.Equals(GetMessageGuid(data), Guid.Empty)) + { + // Session message + _sessionMessageQueue.Add(data); + } + else + { + // Command message + _commandMessageQueue.Add(data); + } } - else + catch (InvalidOperationException) { - // Command message - _commandMessageQueue.Add(data); + // This exception will be thrown by the BlockingCollection message queue objects + // after they have been closed. } }