System.Net.WebSockets.ManagedWebSocket.SendCloseFrameAsync C# (CSharp) Method

SendCloseFrameAsync() private method

Sends a close message to the server.
private SendCloseFrameAsync ( WebSocketCloseStatus closeStatus, string closeStatusDescription, CancellationToken cancellationToken ) : Task
closeStatus WebSocketCloseStatus The close status to send.
closeStatusDescription string The close status description to send.
cancellationToken System.Threading.CancellationToken The CancellationToken to use to cancel the websocket.
return Task
        private async Task SendCloseFrameAsync(WebSocketCloseStatus closeStatus, string closeStatusDescription, CancellationToken cancellationToken)
        {
            // Close payload is two bytes containing the close status followed by a UTF8-encoding of the status description, if it exists.

            byte[] buffer;
            if (string.IsNullOrEmpty(closeStatusDescription))
            {
                buffer = new byte[2];
            }
            else
            {
                buffer = new byte[2 + s_textEncoding.GetByteCount(closeStatusDescription)];
                int encodedLength = s_textEncoding.GetBytes(closeStatusDescription, 0, closeStatusDescription.Length, buffer, 2);
                Debug.Assert(buffer.Length - 2 == encodedLength, $"GetByteCount and GetBytes encoded count didn't match");
            }

            ushort closeStatusValue = (ushort)closeStatus;
            buffer[0] = (byte)(closeStatusValue >> 8);
            buffer[1] = (byte)(closeStatusValue & 0xFF);

            await SendFrameAsync(MessageOpcode.Close, true, new ArraySegment<byte>(buffer), cancellationToken).ConfigureAwait(false);

            lock (StateUpdateLock)
            {
                _sentCloseFrame = true;
                if (_state <= WebSocketState.CloseReceived)
                {
                    _state = WebSocketState.CloseSent;
                }
            }
        }