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?
The key is to wrap Console. ReadLine() in a task.
By using thr. Abort(); statement, we can terminate the execution of the thread.
The first solution is to run the application without debugging by using Ctrl+F5 instead of just F5. The console window will remain open when the program has finished.
Abort may prevent the execution of static constructors or the release of managed or unmanaged resources. For this reason, Thread.
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.
You are going to have to do this differently. One immediately obvious approach is that you let this 'user interface' thread stop the program instead of the other way around. Could be as simple as a "quit" command or the proverbial "Press any key to continue" message.
Or set the thread's IsBackground property to true. Now you don't have to abort it, Windows will terminate it when it shuts down the process after your Main() method exits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With