Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interrupt Console.ReadLine

Tags:

Is it possible to stop the Console.ReadLine() programmatically?

I have a console application: the much of the logic runs on a different thread and in the main thread I accept input using Console.ReadLine(). I'd like to stop reading from console when the separated thread stop running.

How can I achieve this?

like image 669
davioooh Avatar asked Feb 28 '12 09:02

davioooh


People also ask

How do I stop the ReadLine console?

This code sends [enter] into the current console process, aborting any ReadLine() calls blocking in unmanaged code deep within the windows kernel, which allows the C# thread to exit naturally.

What does the console ReadLine () line do?

The ReadLine method reads a line from the standard input stream. (For the definition of a line, see the paragraph after the following list.) This means that: If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key.

What is the use of console ReadLine () in C#?

The C# readline method is mainly used to read the complete string until the user presses the Enter key or a newline character is found. Using this method, each line from the standard data input stream can be read. It is also used to pause the console so that the user can take a look at the output.

What is the shortcut for console ReadLine?

There is no shortcut(code snippet) for Console. ReadLine() .


2 Answers

UPDATE: this technique is no longer reliable on Windows 10. Don't use it please.
Fairly heavy implementation changes in Win10 to make a console act more like a terminal. No doubt to assist in the new Linux sub-system. One (unintended?) side-effect is that CloseHandle() deadlocks until a read is completed, killing this approach dead. I'll leave the original post in place, only because it might help somebody to find an alternative.

UPDATE2: Look at wischi's answer for a decent alternative.


It's possible, you have to jerk the floor mat by closing the stdin stream. This program demonstrates the idea:

using System; using System.Threading; using System.Runtime.InteropServices;  namespace ConsoleApplication2 {     class Program {         static void Main(string[] args) {             ThreadPool.QueueUserWorkItem((o) => {                 Thread.Sleep(1000);                 IntPtr stdin = GetStdHandle(StdHandle.Stdin);                 CloseHandle(stdin);             });             Console.ReadLine();         }          // P/Invoke:         private enum StdHandle { Stdin = -10, Stdout = -11, Stderr = -12 };         [DllImport("kernel32.dll")]         private static extern IntPtr GetStdHandle(StdHandle std);         [DllImport("kernel32.dll")]         private static extern bool CloseHandle(IntPtr hdl);     } } 
like image 148
Hans Passant Avatar answered Sep 19 '22 00:09

Hans Passant


Send [enter] to the currently running console app:

    class Program     {         [DllImport("User32.Dll", EntryPoint = "PostMessageA")]         private static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);          const int VK_RETURN = 0x0D;         const int WM_KEYDOWN = 0x100;          static void Main(string[] args)         {             Console.Write("Switch focus to another window now.\n");              ThreadPool.QueueUserWorkItem((o) =>             {                 Thread.Sleep(4000);                  var hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;                 PostMessage(hWnd, WM_KEYDOWN, VK_RETURN, 0);             });              Console.ReadLine();              Console.Write("ReadLine() successfully aborted by background thread.\n");             Console.Write("[any key to exit]");             Console.ReadKey();         }     } 

This code sends [enter] into the current console process, aborting any ReadLine() calls blocking in unmanaged code deep within the windows kernel, which allows the C# thread to exit naturally.

I used this code instead of the answer that involves closing the console, because closing the console means that ReadLine() and ReadKey() are permanently disabled from that point on in the code (it will throw an exception if its used).

This answer is superior to all solutions that involve SendKeys and Windows Input Simulator, as it works even if the current app does not have the focus.

like image 42
Contango Avatar answered Sep 18 '22 00:09

Contango