private int waitForAdditionalInstances(string[] args) { var accumulatedArgs = new List <string>(args); while (true) { var signal = new ManualResetEvent(false); using (var pipeServer = new NamedPipeServerStream(ipcNamedPipeGuid, PipeDirection.In, -1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous)) { pipeServer.BeginWaitForConnection(x => { // if timed out, stop waiting for a connection if (signal.WaitOne(0)) { signal.Close(); return; } pipeServer.EndWaitForConnection(x); signal.Set(); }, null); // no client connected to the pipe within the Timeout period if (!signal.WaitOne(Timeout, true)) { signal.Set(); break; } using (var sr = new StreamReader(pipeServer)) { int length = Convert.ToInt32(sr.ReadLine()); for (int i = 0; i < length; ++i) { accumulatedArgs.Add(sr.ReadLine()); } } } // new args have been added to accumulatedArgs, continue loop to listen for another client } ipcMutex.Close(); var eventArgs = new SingleInstanceEventArgs(accumulatedArgs.ToArray()); Launching?.Invoke(this, eventArgs); return(eventArgs.ExitCode); }
private int sendArgsToExistingInstance(string[] args) { var pipeClient = new NamedPipeClientStream(".", ipcNamedPipeGuid, PipeDirection.Out); // try to connect to the pipe server for the Timeout period try { var sb = new StringBuilder(); sb.AppendLine(args.Length.ToString()); foreach (string arg in args) { sb.AppendLine(arg); } byte[] buffer = Encoding.ASCII.GetBytes(sb.ToString()); pipeClient.Connect(Timeout); // can this ever happen? if it does, don't handle it like a timeout exception if (!pipeClient.IsConnected) { throw new Exception("did not throw exception"); } pipeClient.Write(buffer, 0, buffer.Length); return(0); } catch (Exception e) { if (!e.Message.ToLower().Contains("time")) { throw; } // no server was running; launch a new instance var eventArgs = new SingleInstanceEventArgs(args); Launching?.Invoke(this, eventArgs); return(eventArgs.ExitCode); } }