MultiplexedConnection CorrelateConnection(int connectionId, object state)
        {
            MultiplexedPipeConnection connection = null;

            connections.TryGetValue(connectionId, out connection);
            return(connection);
        }
        void ClientAccepted(IAsyncResult asyncResult)
        {
            try
            {
                NamedPipeServerStream pipeListener = asyncResult.AsyncState as NamedPipeServerStream;
                pipeListener.EndWaitForConnection(asyncResult);

                NamedPipeServerStream nextPipeListener = new NamedPipeServerStream(
                    localPipe,
                    PipeDirection.InOut,
                    NamedPipeServerStream.MaxAllowedServerInstances,
                    PipeTransmissionMode.Message,
                    PipeOptions.Asynchronous);
                nextPipeListener.BeginWaitForConnection(ClientAccepted, nextPipeListener);

                try
                {
                    Stream socketStream = pipeListener;

                    EnsureConnection();

                    MultiplexedPipeConnection multiplexedConnection = new MultiplexedPipeConnection(pipeListener, multiplexedOutputStream);
                    multiplexedConnection.Closed += MultiplexedConnectionClosed;
                    lock (connectionLock)
                    {
                        connections.Add(multiplexedConnection.Id, multiplexedConnection);
                    }
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Unable to establish connection: {0}", ex.Message);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Failure accepting client: {0}", ex.Message);
            }
        }
        void MultiplexedConnectionClosed(object sender, EventArgs e)
        {
            MultiplexedPipeConnection connection = (MultiplexedPipeConnection)sender;

            connections.Remove(connection.Id);
        }