Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 748
Contango Avatar asked Jan 24 '12 09:01

Contango


People also ask

How do I get rid of console ReadLine?

The key is to wrap Console. ReadLine() in a task.

How do you terminate a thread in C#?

By using thr. Abort(); statement, we can terminate the execution of the thread.

How do I stop the console from closing in C#?

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.

Why is thread abort deprecated?

Abort may prevent the execution of static constructors or the release of managed or unmanaged resources. For this reason, Thread.


1 Answers

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.

like image 91
Hans Passant Avatar answered Sep 22 '22 18:09

Hans Passant