Reputation: 15598
I am trying to figure out why a program I am working on goes in to "not responding" mode when I ask it to output a large amount of characters to the console it is running in.
I tried creating a small example that just prints out characters, and this will indeed also go "not responding" on me after some 10-20 seconds:
static void Main(string[] args)
{
for (int i = 0; i < 255; i = (i+1) % 255)
{
Console.Write(((char)i));
}
}
The program is still running though, even though the console window is "not responding", I can still pause the debugger and continue it, but the console window is broken.
The thing is, the console do not mind spitting out an endless amount of integers:
static void Main(string[] args)
{
for (int i = 0; i < 255; i = (i+1) % 255)
{
Console.Write(i);
}
}
Any ideas is much appreaciated. Thanks!
Upvotes: 2
Views: 728
Reputation: 21752
Just as an aside, you can omit i<255
and simply write:
for (int i = 0; ;i = (i+1) % 255 )
or to go with Jon's answer you can simplify that like this
using System;
class Test
{
static void Main(string[] args)
{
for(var i=0;;i=(i+1) % 126)
{
Console.Write((char)(i+32));
}
}
}
Upvotes: 1
Reputation: 1502835
Well it will spew out a lot of nonsense (and beep a lot, unless you mask out character 7, which is a bell) but it never becomes unresponsive for me.
It will depend on how your console handles control characters though - which console are you using, on which operating system and with which language?
Moreover, why do you want to send unprintable characters to the console? If you keep your loop to ASCII (32-126) what happens? For example:
using System;
class Test
{
static void Main(string[] args)
{
int i=32;
while (true)
{
Console.Write((char)i);
i++;
if (i == 127)
{
i = 32;
}
}
}
}
Does that still exhibit the same behaviour?
You mention the debugger - do you get the same behaviour if you run outside the debugger? (I've only tested from the command line so far.)
Upvotes: 4
Reputation: 416081
When you cast it to a character, you're also sending control characters to the console for some lower values of i
. I'd guess is has something to do with outputting some of those control characters repeatedly.
Upvotes: 5