Example #1
0
        private async void CreateOutputPipe(string id, CancellationToken cancellationToken)
        {
            using (NamedPipeServerStream pipeServer =
                       new NamedPipeServerStream(OutputPipeName, PipeDirection.InOut, _maxConnections))
            {
                Trace.TraceInformation($"Server {id} waiting for connection ...");
                await _semaphoreStartOutputConnections.WaitAsync(cancellationToken);

                try
                {
                    await pipeServer.WaitForConnectionAsync(cancellationToken);
                }
                catch (Exception e)
                {
                    Trace.TraceError("Error waiting for pipe connection: {0}", e.Message);
                }
                finally { _semaphoreStartOutputConnections.Release(); }
                Trace.TraceInformation($"Client connected on id: {id}");
                try
                {
                    StreamString ss       = new StreamString(pipeServer, pipeServer);
                    string       clientId = await ss.ReadString(cancellationToken);

                    lock (_syncRootClients)
                    {
                        if (_pendingClients.TryGetValue(clientId, out NamedPipeIpcClient val))
                        {
                            if (val.OutputPipe == null)
                            {
                                val.OutputPipe = pipeServer;
                                _clients.Add(val.Id, val);
                                _pendingClients.Remove(val.Id);
                            }
                            else
                            {
                                Trace.TraceWarning("Client tried to register two input pipes.");
                                pipeServer.Close();
                            }
                        }
                        else
                        {
                            _clients.Add(clientId, new NamedPipeIpcClient(clientId)
                            {
                                OutputPipe = pipeServer
                            });
                        }
                    }
                }
                catch (IOException e)
                {
                    Trace.TraceError(e.Message);
                }
                catch (ArgumentException)
                {
                    Trace.TraceInformation("Client ? disconnected.");
                }
            }
        }