private void BeginRead(IpcPipeData pd)
        {
            // Asynchronously read a request from the client
            bool isConnected = pd.pipe.IsConnected;

            if (isConnected)
            {
                try
                {
                    pd.pipe.BeginRead(pd.data, 0, pd.data.Length, OnAsyncMessage, pd);
                }
                catch (Exception)
                {
                    isConnected = false;
                }
            }

            if (!isConnected)
            {
                pd.pipe.Close();
                m_callback.OnAsyncDisconnect(pd.pipe, pd.state);
                lock (m_pipes)
                {
                    bool removed = m_pipes.Remove(pd.pipe);
                    Debug.Assert(removed);
                }
            }
        }
        private void OnAsyncMessage(IAsyncResult result)
        {
            // Async read from client completed
            IpcPipeData pd        = (IpcPipeData)result.AsyncState;
            Int32       bytesRead = pd.pipe.EndRead(result);

            if (bytesRead != 0)
            {
                m_callback.OnAsyncMessage(pd.pipe, pd.data, bytesRead, pd.state);
            }
            BeginRead(pd);
        }
        private void OnClientConnected(IAsyncResult result)
        {
            // Complete the client connection
            NamedPipeServerStream pipe = (NamedPipeServerStream)result.AsyncState;

            pipe.EndWaitForConnection(result);

            // Create client pipe structure
            IpcPipeData pd = new IpcPipeData();

            pd.pipe  = pipe;
            pd.state = null;
            pd.data  = new Byte[SERVER_IN_BUFFER_SIZE];

            // Add connection to connection list
            bool running;

            lock (m_pipes)
            {
                running = m_running;
                if (running)
                {
                    m_pipes.Add(pd.pipe, pd);
                }
            }

            // If server is still running
            if (running)
            {
                // Prepare for next connection
                IpcServerPipeCreate();

                // Alert server that client connection exists
                m_callback.OnAsyncConnect(pipe, out pd.state);

                // Accept messages
                BeginRead(pd);
            }
            else
            {
                pipe.Close();
            }
        }