Commit 349865ac authored by Matt Hyman's avatar Matt Hyman
Browse files

Move .Net Websocket ListenForMessagesInternal logic to background thread to...

Move .Net Websocket ListenForMessagesInternal logic to background thread to prevent deadlock when closing websocket.
parent a35f6a06
Loading
Loading
Loading
Loading
+53 −49
Original line number Diff line number Diff line
@@ -38,9 +38,9 @@ namespace Microsoft.Tools.WindowsDevicePortal
        private ClientWebSocket websocket = new ClientWebSocket();

        /// <summary>
        /// <see cref="ManualResetEvent" /> used to indicate that the <see cref="WebSocket{T}" /> has stopped receiving messages.
        /// <see cref="Task" /> for receiving messages.
        /// </summary>
        private ManualResetEvent stoppedReceivingMessages = new ManualResetEvent(false);
        private Task receivingMessagesTask;

        /// <summary>
        /// The handler used to validate server certificates.
@@ -95,8 +95,8 @@ namespace Microsoft.Tools.WindowsDevicePortal
                // Wait for web socket to no longer be receiving messages.
                if (this.IsListeningForMessages)
                {
                    this.stoppedReceivingMessages.WaitOne();
                    this.stoppedReceivingMessages.Reset();
                    await this.receivingMessagesTask;
                    this.receivingMessagesTask = null;
                }

                // Reset websocket as WDP will abort the connection once it receives the close message.
@@ -109,6 +109,8 @@ namespace Microsoft.Tools.WindowsDevicePortal
        /// </summary>
        /// <returns>The task of listening for messages from the websocket.</returns>
        private async Task ListenForMessagesInternal()
        {
            this.receivingMessagesTask = Task.Run(async () =>
            {
                try
                {
@@ -173,9 +175,11 @@ namespace Microsoft.Tools.WindowsDevicePortal
                }
                finally
                {
                this.stoppedReceivingMessages.Set();
                    this.IsListeningForMessages = false;
                }
            });

            await this.receivingMessagesTask;
        }

        /// <summary>