Reputation: 984
I have a program that listens to the console stdin stream.
Read()
returns, every character is read out one by one and passed to method()
. method()
then appends the character to a StringBuilder
. '\n'
, then method()
calls respond()
, which prints out the read characters and clears the StringBuilder
.However, even after typing something in the console and pressing Enter, I have to press/move my mouse, the mouse buttons, or the keyboard within the focus of the console for the text typed to be echoed. Even more mysterious is that when I set a breakpoint in the first curly brace of Main()
and step into every single statement thereafter, the program executes correctly. How can i fix this? Thanks a lot!
public class test
{
static byte[] buffer = new byte[1];
static Stream instrm = Console.OpenStandardInput();
static Stream outstrm = Console.OpenStandardOutput();
static System.Text.StringBuilder sb = new System.Text.StringBuilder();
static void Main()
{
while (true)
{
instrm.Read(buffer, 0, 1);
method(buffer);
}
}
public static void method(byte[] buffer)
{
sb.Append(System.Text.Encoding.UTF8.GetString(buffer));
if (buffer[0] == (byte)10) respond();
}
public static void respond()
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
outstrm.Write(bytes, 0, bytes.Length);
outstrm.Flush();
sb.Clear();
}
}
EDIT:
I just tested and found out that it had nothing to do with the thread, so took the part away. I originally posted it so as it was a problem in my other program, this being only a test model to demonstrate it.
Upvotes: 2
Views: 5803
Reputation: 2733
I would change the program like this:
static byte[] buffer = new byte[1];
static TextReader instrm = new StreamReader(Console.OpenStandardInput());
static TextWriter outstrm = new StreamWriter(Console.OpenStandardOutput());
static StringBuilder sb = new StringBuilder();
static void Main()
{
while (true)
{
var readLine = instrm.ReadLine();
respond(readLine);
}
}
public static void respond(string line)
{
outstrm.Write(line);
outstrm.Flush();
}
It is easier and works. The main difference is to use StreamReader
and StreamWriter
instead for Stream
.
Upvotes: 5