/// <summary> /// Cancel any pending tasks and close the connection. /// </summary> /// <param name="closeStatus">Status to communicate to server, default /// to NormalClosure</param> /// <returns><c>Task</c> to await on.</returns> public override async Task Close(WebSocketCloseStatus closeStatus = WebSocketCloseStatus.NormalClosure) { if (m_CancellationToken.IsCancellationRequested) { // cancellation already requested, no need to do anything return; } m_TokenSource?.Cancel(); if (State == State.Open || State == State.Connecting) { await m_Socket.CloseAsync(closeStatus, string.Empty, CancellationToken.None); } m_Socket?.Dispose(); // Close might be called on pooled thread await synchronizationContext.RunInContext(() => { InvokeOnClose(closeStatus); }); }