.net console app stop responding when printing out lots of chars in a row

这一生的挚爱 提交于 2020-01-15 06:00:12

问题


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!


回答1:


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.)




回答2:


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.




回答3:


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));
        }
    }
}


来源:https://stackoverflow.com/questions/912373/net-console-app-stop-responding-when-printing-out-lots-of-chars-in-a-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!