Commit 222d3099 authored by Matt Hyman's avatar Matt Hyman Committed by GitHub
Browse files

Merge pull request #162 from MattHyman/master

Fix .Net Websocket deadlock scenario on closing websocket
parents 590be6b1 349865ac
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>