473,698 Members | 2,466 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unblock Console.Readlin e 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
WriteConsoleInp ut
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*****@remove this.emsoft.and this.ca> wrote in message
news:#Y1BZAAuCH A.1676@TK2MSFTN GP10...
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.Threa dPool.QueueUser WorkItem(Addres sOf UnblockMe,
Nothing)
Console.ReadLin e()

Console.WriteLi ne("UNBLOCKED" )

Console.ReadLin e()

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

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

MS.WriteByte(13 )
MS.WriteByte(10 )
MS.Seek(0, IO.SeekOrigin.B egin)
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.OpenSt andardInput)
Console.SetIn(O ldStream)
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.readlin e 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 5190
ke****@lucidyne .com (Kevin) wrote in message news:<b6******* *************** ***@posting.goo gle.com>...

OK, Nobody has responded to me. In the meantime, I got the
WriteConsoleInp ut 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.READLIN E
VB.NET

Imports System
Imports System.Threadin g
Imports System.Runtime. InteropServices

Module Module1

Sub Main()
'This will spawn a thread to unblock the ensuing
console.readlin e
Threading.Threa dPool.QueueUser WorkItem(Addres sOf UnblockMe,
Nothing)

Console.ReadLin e()
Console.WriteLi ne("UNBLOCKED" )
Console.ReadLin e()

End Sub

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

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

With InputRecords(0)
.EventType = 1
.bKeyDown = True
.uChar.AsciiCha r = 13
.dwControlKeySt ate = 0
.wRepeatCount = 1
.wVirtualKeyCod e = 0
.wVirtualScanCo de = 0
End With

ConsoleUtils.Wr iteConsoleInput (ConsoleUtils.S TD_INPUT_HANDLE ,
InputRecords, 1, New Integer)

End Sub

End Module
Module ConsoleUtils

<Flags()> Public Enum ControlKeyState As Integer

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

End Enum

<StructLayout(L ayoutKind.Expli cit)> Public Structure CHAR_UNION
<FieldOffset(0) > Public UnicodeChar As Short
<FieldOffset(0) > Public AsciiChar As Byte
End Structure

<DllImport("ker nel32", EntryPoint:="Wr iteConsoleInput A",
CharSet:=CharSe t.Auto, SetLastError:=T rue,
ThrowOnUnmappab lechar:=True)> _
Public Function WriteConsoleInp ut( _
ByVal hConsoleInput As IntPtr, _
ByVal lpBuffer() As KeyEventStruct, _
ByVal nLength As Integer, _
ByVal lpNumberOfEvent sWritten As Integer) As Boolean
End Function

<DllImport("KER NEL32.DLL", EntryPoint:="Ge tStdHandle",
SetLastError:=F alse, ExactSpelling:= True,
CallingConventi on:=CallingConv ention.StdCall) > _
Public Function GetStdHandle( _
ByVal nStdHandle As Integer) As Integer
End Function

<StructLayout(L ayoutKind.Seque ntial)> Public Structure
KeyEventStruct
Public EventType As Short
<MarshalAs(Unma nagedType.Bool) > Public bKeyDown As Boolean
Public wRepeatCount As Short
Public wVirtualKeyCode As Short
Public wVirtualScanCod e As Short
Public uChar As CHAR_UNION
Public dwControlKeySta te As ControlKeyState
End Structure

'Public ReadOnly STD_OUTPUT_HAND LE As IntPtr = New
IntPtr(GetStdHa ndle(-11))
Public ReadOnly STD_INPUT_HANDL E As IntPtr = New
IntPtr(GetStdHa ndle(-10))
'Public ReadOnly STD_ERROR_HANDL E As IntPtr = New
IntPtr(GetStdHa ndle(-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
WriteConsoleInp ut
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*****@remove this.emsoft.and this.ca> wrote in message
news:#Y1BZAAuCH A.1676@TK2MSFTN GP10...
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.Threa dPool.QueueUser WorkItem(Addres sOf UnblockMe,
Nothing)
Console.ReadLin e()

Console.WriteLi ne("UNBLOCKED" )

Console.ReadLin e()

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

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

MS.WriteByte(13 )
MS.WriteByte(10 )
MS.Seek(0, IO.SeekOrigin.B egin)
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.OpenSt andardInput)
Console.SetIn(O ldStream)
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.readlin e 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
2692
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 T2, T3... try to enter the critical section and are blocked. What is the order that the threads get to enter the critical section?
7
1723
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 where the math is involved. Thanks. using System; using System.Threading;
8
18650
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 available in the same form for users to enter commands and display outputs if some prefer to use character based user interface. I would like to implement the user interface in vb .net. Now I have menus and toolbars ready, but do not now how to get a...
6
5960
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 codeproject and msdn. http://www.codeproject.com/csharp/LaunchProcess.asp http://msdn.microsoft.com/msdnmag/issues/03/02/Multithreading/default.aspx In the eample Standard out is read like this:
1
4931
by: Joachim | last post by:
Is there a way to set a timeout for the Console.ReadLine method?
2
14376
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 proceed further with the program logic. I had a difficulty in implementing this, as console.readline() indefinitely waits for the user input.
6
1714
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 the micq and then act upon them. I've been using the System.Diagnostics.Process class and redirecting the input and output stream. R eading the output works fine, but I am not able to send any commands to the application. Or better, micq doesn't...
4
3570
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 the stdin... Thanks in advance, João
0
1430
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 Miscellaenous section at http://twistedmatrix.com/projects/core/documentation/examples/ Jean-Paul
0
8678
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9166
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8871
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7737
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6525
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5861
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4621
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3052
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 we have to send another system
2
2333
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.