473,506 Members | 11,491 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 5170
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
2668
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 the critical section) Now suppose more threads...
7
1714
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 it better/cleaner/more efficient, etc. especially...
8
18618
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 same time, I would like to have a console window...
6
5942
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 implemented the code from the following example on...
1
4916
by: Joachim | last post by:
Is there a way to set a timeout for the Console.ReadLine method?
2
14319
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 there is no input in that time, I would like to...
6
1704
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 want to be able to send an receive messages through...
4
3553
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 actually work ... something to put characters in...
0
1414
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 Windows. See stdiodemo.py and stdin.py under the...
0
7220
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7105
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7308
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7371
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7023
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5617
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
4702
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1534
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
757
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.