如何在以下代码中防止StackOverflow错误?

时间:2009-04-27 01:07:51

标签: c# console

我有以下代码,为WCF控制台托管应用程序提供自动刷新功能。

当Console.ReadKey接受无效字符时,它会重新启动ReadKey方法。如果用户在此代码上对键盘进行足够长时间的混乱,则会进入StackOverflowException。

有没有人有办法重新编写这段代码,以免它导致堆栈爆炸?

[STAThread]
static void Main(string[] args)
{
    bool restart = true;
    while(restart)
    {
        using (var myWcfHost = new MyWcfHost())
        {
            myWcfHost.start();

            Console.WriteLine("Press Enter to quit or Ctrl+R to restart");

            restart = WaitForRestart();
        }
    }
}

private static bool WaitForRestart()
{
    // clear users input
    Console.CursorLeft = 0;
    Console.Write(' ');
    Console.CursorLeft = 0;

    // read users input
    var key = Console.ReadKey();
    if ((key.Modifiers & ConsoleModifiers.Control) != 0
        && key.Key == ConsoleKey.R)
    {
        // refersh the settings
        ConfigurationManager.RefreshSection("appSettings");
        return true;
    }
    if (key.Key == ConsoleKey.Enter || key.Key == ConsoleKey.Escape)
    {
        return false;
    }
    return WaitForRestart();
}

2 个答案:

答案 0 :(得分:3)

用循环替换递归:

private static bool WaitForRestart()
{
    while (true)
    {
        // clear users input
        Console.CursorLeft = 0;
        Console.Write(' ');
        Console.CursorLeft = 0;

        // read users input
        var key = Console.ReadKey();
        if ((key.Modifiers & ConsoleModifiers.Control) != 0
            && key.Key == ConsoleKey.R)
        {
            // refersh the settings
            ConfigurationManager.RefreshSection("appSettings");
            return true;
        }
        if (key.Key == ConsoleKey.Enter || key.Key == ConsoleKey.Escape)
        {
            return false;
        }
    }
}

答案 1 :(得分:0)

看起来每次按下无效键时,您将另一个WaitForRestart推入堆栈,最终导致溢出异常。我想这会解决:

private static bool WaitForRestart()
{
// clear users input
Console.CursorLeft = 0;
Console.Write(' ');
Console.CursorLeft = 0;


while (true) 
{
    // read users input
    var key = Console.ReadKey();
    if ((key.Modifiers & ConsoleModifiers.Control) != 0
        && key.Key == ConsoleKey.R)
    {
        // refersh the settings
        ConfigurationManager.RefreshSection("appSettings");
        return true;
    }
    if (key.Key == ConsoleKey.Enter || key.Key == ConsoleKey.Escape)
    {
        return false;
    }
}
}