public static void AttachToConsole(int processId, TimeSpan timeout) { ConsoleInterface.callWin32Func(() => NativeInterface.FreeConsole()); DateTime startTime = DateTime.Now; do { if (NativeInterface.AttachConsole(processId)) { return; } } while (startTime + timeout > DateTime.Now); throw new TimeoutException(); }