public async Task Open(Server server, CancellationToken cancellationToken) { var process = Process.GetProcessById(server.ProcessId); var whenProcessExits = Observable.FromEventPattern(h => process.Exited += h, h => process.Exited -= h); process.EnableRaisingEvents = true; if (process.HasExited) { ThrowProcessExitedError(); } var connectionModel = new ConnectionModel(server); mActiveConnection.Disposable = connectionModel.Connect(); bool connected = await connectionModel.WhenConnected.Where(isConnected => isConnected) .Merge(whenProcessExits.Select(_ => false)) .Take(1) .ToTask(cancellationToken); if (!connected) { ThrowProcessExitedError(); } mConnectionSubject.OnNext(connectionModel); void ThrowProcessExitedError() { throw new ConnectionException($"Process exited before communication was established."); } }