private void notifyError(Exception cause)
        {
            try {
                long currentState = Interlocked.Read(ref state);

                if (currentState == CLOSING)
                {
                    if (Interlocked.CompareExchange(ref state, CLOSED, currentState) == currentState)
                    {
                        listener.OnClose(1000, "");
                    }
                }
                else if (currentState != CLOSED)
                {
                    if (Interlocked.CompareExchange(ref state, CLOSED, currentState) == currentState)
                    {
                        listener.OnError(cause);
                    }
                }
            } catch (Exception) {
                // discard exceptions thrown by the listener
            }
            return;
        }