Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to abort another thread in .NET, when said thread is executing Console.ReadLine?
    primarykey
    data
    text
    <p>My console app is executing a thread that is totally devoted to the user interface, it spends a lot of its time blocking on <code>Console.ReadLine()</code> (this call spends its time deep within the bowels of Windows, outside the control of the .NET framework).</p> <p>I need to abort this thread. However, the following code doesn't seem to work:</p> <pre><code>this.UserInterfaceThread.Abort(); </code></pre> <p>Any ideas? Would Thread.Interrupt() be of any use?</p> <p><strong><em>Update</em></strong></p> <p>As Hans Passant pointed out:</p> <blockquote> <p>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.</p> </blockquote> <p>The solution is to simply poke the [enter] keystroke into the currently running console app, which unblocks Console.ReadLine(), so the thread immediately aborts.</p> <p>We <em>cannot</em> use SendKeys as this is specific to windows forms, and it also requires the current window to have the focus. </p> <p>The solution is to use the library at <a href="http://inputsimulator.codeplex.com/" rel="nofollow noreferrer">inputsimulator.codeplex.com</a> which wraps the Windows SendInput() call.</p> <p>See sample code:</p> <p><a href="https://stackoverflow.com/questions/9016087/net-call-to-send-enter-keystroke-into-the-current-process-which-is-a-console">.NET call to send [enter] keystroke into the current process, which is a console app?</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload