472,331 Members | 1,469 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,331 software developers and data experts.

Unblock Console.Readline from a separate thread

In a newsgroup thread from Jan 8, 2003 between Barry Holsinger and the
VBDotNet Team, please review this excerpt:
"You understood my problem completely. Your sample code provides a
really
elegant way to inject CrLf into the input stream, which effectively
unblocks
the ReadLine method. Last night, I had finally got the
WriteConsoleInput
API function to work correctly from VB.NET, and now I see these few
lines of
code from you that do the whole thing without resorting to kernel32
calls.

All I can say is... I wish I'd found this newsgroup two weeks ago!

Many thanks,
barryh

"Stephen Martin" <sm*****@removethis.emsoft.andthis.ca> wrote in message
news:#Y1BZAAuCHA.1676@TK2MSFTNGP10...
This was an interesting puzzle. If I understand correctly you want to
unblock a ReadLine request under certain circumstances, do something, and
then probably go back to reading from the console. You couldn't unblock it
on the main thread so you're putting it on another thread and trying to
abort the thread rather than unblock the read. First bit of advice is that
if any solution to a normal occurrence in your program involves calling
Thread.Abort then you are probably making going down the wrong path. Threads
should die naturally - Abort is really only for very unusual circumstances.
As to your problem the solution is to reset the standard in to another
stream, write a CrLf to that stream to unblock and then later reacquire the
standard in. It is a bit difficult to explain so I threw together a very
quick, rough example that I am attaching. This example uses separate
threads, that are created and die as needed, for console reading but it
could easily be modified to use the main thread .

HTH

"

This is EXACTLY where I'm at and it seems that I've traveled the same
path as Mr Holsinger. To try and follow what the VBDotNET team is
saying to do I've done the following:

A console app's sub main,

Sub Main()
Threading.ThreadPool.QueueUserWorkItem(AddressOf UnblockMe,
Nothing)
Console.ReadLine()

Console.WriteLine("UNBLOCKED")

Console.ReadLine()

End Sub
End Module
Private Sub UnblockMe(ByVal state As Object)
Threading.Thread.CurrentThread.Sleep(1000)

Dim MS As New IO.MemoryStream
Dim NewStream As New IO.StreamReader(MS)
Try
Console.SetIn(NewStream)

MS.WriteByte(13)
MS.WriteByte(10)
MS.Seek(0, IO.SeekOrigin.Begin)
MS.Flush()
Catch
If Not MS Is Nothing Then
MS.Close()
End If
If Not NewStream Is Nothing Then
NewStream.Close()
End If
End Try

'Put the Standard In stream back
Dim OldStream As New IO.StreamReader(Console.OpenStandardInput)
Console.SetIn(OldStream)
End Sub
This obviously is not the code to my working program, but it outlines
the crux of what I'm trying to accomplish. I need to unblock the
console.readline from a separate thread, and the above code isn't
working. And the code excerpt wasn't included in the newsgroup thread
that I was interested in.

PLEASE HELP!

Thank you and sincerely,
Kevin
Nov 21 '05 #1
1 4952
ke****@lucidyne.com (Kevin) wrote in message news:<b6*************************@posting.google.c om>...

OK, Nobody has responded to me. In the meantime, I got the
WriteConsoleInput API call working. Here's the code for anybody else
that needs it, minus error handling.

I would still be interested in the Code that Barry Holsinger received
in the indicated thread.
CODE TO UNBLOCK A PENDING CONSOLE.READLINE
VB.NET

Imports System
Imports System.Threading
Imports System.Runtime.InteropServices

Module Module1

Sub Main()
'This will spawn a thread to unblock the ensuing
console.readline
Threading.ThreadPool.QueueUserWorkItem(AddressOf UnblockMe,
Nothing)

Console.ReadLine()
Console.WriteLine("UNBLOCKED")
Console.ReadLine()

End Sub

Private Sub UnblockMe(ByVal state As Object)
Threading.Thread.CurrentThread.Sleep(1000)

Dim InputRecords(0) As KeyEventStruct
InputRecords(0) = New KeyEventStruct

With InputRecords(0)
.EventType = 1
.bKeyDown = True
.uChar.AsciiChar = 13
.dwControlKeyState = 0
.wRepeatCount = 1
.wVirtualKeyCode = 0
.wVirtualScanCode = 0
End With

ConsoleUtils.WriteConsoleInput(ConsoleUtils.STD_IN PUT_HANDLE,
InputRecords, 1, New Integer)

End Sub

End Module
Module ConsoleUtils

<Flags()> Public Enum ControlKeyState As Integer

RightAltPressed = &H1
LeftAltPressed = &H2
RightCtrlPressed = &H4
LeftCtrlPressed = &H8
ShiftPressed = &H10
NumLockOn = &H20
ScrollLockOn = &H40
CapsLockOn = &H80
EnhancedKey = &H100

End Enum

<StructLayout(LayoutKind.Explicit)> Public Structure CHAR_UNION
<FieldOffset(0)> Public UnicodeChar As Short
<FieldOffset(0)> Public AsciiChar As Byte
End Structure

<DllImport("kernel32", EntryPoint:="WriteConsoleInputA",
CharSet:=CharSet.Auto, SetLastError:=True,
ThrowOnUnmappablechar:=True)> _
Public Function WriteConsoleInput( _
ByVal hConsoleInput As IntPtr, _
ByVal lpBuffer() As KeyEventStruct, _
ByVal nLength As Integer, _
ByVal lpNumberOfEventsWritten As Integer) As Boolean
End Function

<DllImport("KERNEL32.DLL", EntryPoint:="GetStdHandle",
SetLastError:=False, ExactSpelling:=True,
CallingConvention:=CallingConvention.StdCall)> _
Public Function GetStdHandle( _
ByVal nStdHandle As Integer) As Integer
End Function

<StructLayout(LayoutKind.Sequential)> Public Structure
KeyEventStruct
Public EventType As Short
<MarshalAs(UnmanagedType.Bool)> Public bKeyDown As Boolean
Public wRepeatCount As Short
Public wVirtualKeyCode As Short
Public wVirtualScanCode As Short
Public uChar As CHAR_UNION
Public dwControlKeyState As ControlKeyState
End Structure

'Public ReadOnly STD_OUTPUT_HANDLE As IntPtr = New
IntPtr(GetStdHandle(-11))
Public ReadOnly STD_INPUT_HANDLE As IntPtr = New
IntPtr(GetStdHandle(-10))
'Public ReadOnly STD_ERROR_HANDLE As IntPtr = New
IntPtr(GetStdHandle(-12))

End Module
Sincerely,

Kevin C.

In a newsgroup thread from Jan 8, 2003 between Barry Holsinger and theVBDotNet Team, please review this excerpt: "You understood my problem completely. Your sample code provides a
really
elegant way to inject CrLf into the input stream, which effectively
unblocks
the ReadLine method. Last night, I had finally got the
WriteConsoleInput
API function to work correctly from VB.NET, and now I see these few
lines of
code from you that do the whole thing without resorting to kernel32
calls.

All I can say is... I wish I'd found this newsgroup two weeks ago!

Many thanks,
barryh

"Stephen Martin" <sm*****@removethis.emsoft.andthis.ca> wrote in message
news:#Y1BZAAuCHA.1676@TK2MSFTNGP10...
This was an interesting puzzle. If I understand correctly you want to
unblock a ReadLine request under certain circumstances, do something, and
then probably go back to reading from the console. You couldn't unblock it
on the main thread so you're putting it on another thread and trying to
abort the thread rather than unblock the read. First bit of advice is that
if any solution to a normal occurrence in your program involves calling
Thread.Abort then you are probably making going down the wrong path. Threads
should die naturally - Abort is really only for very unusual circumstances.
As to your problem the solution is to reset the standard in to another
stream, write a CrLf to that stream to unblock and then later reacquire the
standard in. It is a bit difficult to explain so I threw together a very
quick, rough example that I am attaching. This example uses separate
threads, that are created and die as needed, for console reading but it
could easily be modified to use the main thread .

HTH

"

This is EXACTLY where I'm at and it seems that I've traveled the same
path as Mr Holsinger. To try and follow what the VBDotNET team is
saying to do I've done the following:

A console app's sub main,

Sub Main()
Threading.ThreadPool.QueueUserWorkItem(AddressOf UnblockMe,
Nothing)
Console.ReadLine()

Console.WriteLine("UNBLOCKED")

Console.ReadLine()

End Sub
End Module
Private Sub UnblockMe(ByVal state As Object)
Threading.Thread.CurrentThread.Sleep(1000)

Dim MS As New IO.MemoryStream
Dim NewStream As New IO.StreamReader(MS)
Try
Console.SetIn(NewStream)

MS.WriteByte(13)
MS.WriteByte(10)
MS.Seek(0, IO.SeekOrigin.Begin)
MS.Flush()
Catch
If Not MS Is Nothing Then
MS.Close()
End If
If Not NewStream Is Nothing Then
NewStream.Close()
End If
End Try

'Put the Standard In stream back
Dim OldStream As New IO.StreamReader(Console.OpenStandardInput)
Console.SetIn(OldStream)
End Sub
This obviously is not the code to my working program, but it outlines
the crux of what I'm trying to accomplish. I need to unblock the
console.readline from a separate thread, and the above code isn't
working. And the code excerpt wasn't included in the newsgroup thread
that I was interested in.

PLEASE HELP!

Thank you and sincerely,
Kevin

Nov 21 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

25
by: vooose | last post by:
Suppose execution of a particular thread T1 hits Monitor.Enter(obj); //critical section and blocks at the first line. (ie someone else is in...
7
by: John Salerno | last post by:
Ok, here's an attempt at something. I figure I can use this to let me know when my laundry's done! :) I'm hoping you guys can spot ways to make...
8
by: Alison | last post by:
Hi, Al I am trying to design a user interface which provides both menus and toolbars for some users to click on whatever they want to do, at the...
6
by: MeowCow | last post by:
I will try and make my question with out being too long winded. I have been doing a lot of reading on how to do multithreading and I have...
1
by: Joachim | last post by:
Is there a way to set a timeout for the Console.ReadLine method?
2
by: SriBhargav | last post by:
Hi, I've a question on setting timeout on console.readline() I would like the user to input something through Console.readline() in 5 secs. If...
6
by: dolulob | last post by:
Hi, I'm trying to communicate with a console application through a c# program. the console application is micq a console based ICQ client. I...
4
by: joamag | last post by:
HI, Is there any possible way to unblock the sys.stdin.readline() call from a different thread. Something like sys.stdin.write() but that would...
0
by: Jean-Paul Calderone | last post by:
On Sat, 21 Jun 2008 12:35:02 -0700 (PDT), joamag <joamag@gmail.comwrote: Twisted supports asynchronous handling of stdin on both POSIX and...
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: CD Tom | last post by:
This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.