private void OnConnect(IAsyncResult asyncResult)
        {
            var srv = (NamedPipeServerStream)asyncResult.AsyncState;

            try
            {
                srv.EndWaitForConnection(asyncResult);
            }
            catch (ObjectDisposedException)
            {
                return;
            }

            CreateListener();

            if (!CheckPipeAuthorization(srv))
            {
                Log.Warning("Disconnecting unauthorized client.");
                srv.Close();
                srv.Dispose();
                return;
            }

            PipeMessenger messenger = null;

            try
            {
                var outStream = CreateOutputStream(srv);
                messenger = new PipeMessenger(srv, outStream);

                PipeConnected?.Invoke(this, new PipeConnectionArgs(messenger));

                messenger.RunReadMessageLoop();

                PipeDisconnected?.Invoke(this, new PipeConnectionArgs(messenger));
                Log.Information("Named pipe client disconnected.");
            }
            catch (Exception ex)
            {
                Log.Warning(ex);
            }

            messenger?.Dispose();
            bool dummy;

            this.pipeServers.TryRemove(srv, out dummy);
        }
 public void Disconnect()
 {
     PipeDisconnected?.Invoke(this, new PipeConnectionArgs(this.messenger));
 }