コード例 #1
0
        public void WaitForConnectionCancelableAndDispose()
        {
            var pipeName = Helper.CreatePipeName();
            var streams  = new NamedPipeServerStreams(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

            Task.Run(() => streams.WaitForConnectionCancelable());
            Thread.Sleep(100);
            streams.Dispose();
        }
コード例 #2
0
        private void Communication()
        {
            string exitReason = "None";

            try {
                Debug.WriteLine($"[Server {InstanceId}] Communication Started");
                if (!_streams.WaitForConnectionCancelable())
                {
                    exitReason = "Connect canceled"; return;
                }
                Debug.WriteLine($"[Server {InstanceId}] Communication Connected");
                Connected?.Invoke(this, EventArgs.Empty);

                while (true)
                {
                    if (_disposeFlag)
                    {
                        exitReason = "Disposed"; break;
                    }
                    if (_streams.Reader.EndOfStream)
                    {
                        exitReason = "EndOfStream"; break;
                    }

                    var request = _streams.Reader.ReadLine();                     // TODO read strategy message/byte/line
                    Debug.WriteLine($"[Server {InstanceId}] Communication Received");

                    if (request != null)
                    {
                        var msgEventArgs = new PipeMsgEventArgs(request);
                        RequestReceived.Invoke(this, msgEventArgs);
                        _streams.Writer.WriteLine(msgEventArgs.Response);
                        _streams.Writer.Flush();
                    }
                }
            }
            catch (IOException ex) {
                exitReason = "IOException";
                Debug.WriteLine(ex);
            }
            catch (Exception ex) {
                exitReason = "Exeption";
                Debug.WriteLine(ex);
            }
            finally {
                Debug.WriteLine($"[Server {InstanceId}] Communication exit. Reason: {exitReason}");
                Disconnected?.Invoke(this, EventArgs.Empty);
                Dispose();
            }
        }