Alex Rivera | Logout

How to abort another thread in .NET, when said thread is executing Console.ReadLine?

Asked 2012-01-24T09:59:11.930
10

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?

Edit
Report

2 Answers

6

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.

answered 2012-01-24T11:32:26.380
4

Use SendKeys and simulate ENTER key. Get help here.

Good luck.

answered 2012-01-24T10:53:00.430

Your Answer