My console app is executing a thread that is totally devoted to the user interface, it spends a lot of its time blocking on Console.ReadLine()
(this call spends its time deep within the bowels of Windows, outside the control of the .NET framework).
I need to abort this thread. However, the following code doesn't seem to work:
this.UserInterfaceThread.Abort();
Any ideas? Would Thread.Interrupt() be of any use?
Update
As Hans Passant pointed out:
The CLR imposes rather sane rules on the state of a thread when it aborts it. The perils of Thread.Abort() are well known, what certainly cannot ever work reliably is aborting a thread that's executing unmanaged code. Which is the case when you call Console.ReadLine(), the thread is buried deep inside Windows operating system code.
The solution is to simply poke the [enter] keystroke into the currently running console app, which unblocks Console.ReadLine(), so the thread immediately aborts.
We cannot use SendKeys as this is specific to windows forms, and it also requires the current window to have the focus.
The solution is to use the library at inputsimulator.codeplex.com which wraps the Windows SendInput() call.
See sample code:
.NET call to send [enter] keystroke into the current process, which is a console app?