如何在C#上的控制台应用程序中停止使用键盘输入的运行方法?

Gir*_*rdi 6 c# user-input input break while-loop

简而言之,我正在利用C#进行科学计算,并且我编写了一个方法,该方法具有可以运行到用户指定数量的步骤的while循环......实际上,这种方法可能需要很长时间才能执行(如更多超过5小时).如果需要这么长时间,我可能想要停止方法Esc按键,例如.

当我读到关于破坏的东西时while,它就像Boolean旗帜或类似的东西一样简单.所以我想到这样的事情:

public Double? Run(int n)
{
    int i = 0;
    while ((i < n) && (/* inputkey != ConsoleKey.Escape */))
    {
        // here goes the heavy computation thing
        // and I need to read some "inputkey" as well to break this loop
        i++;
    }
    // I'm not worried about the return statement, as it is easy to do...
    // returns null if the user skipped the method by pressing Escape
    // returns null if the method didn't converged
    // returns the double value that the method calculated otherwise
}
Run Code Online (Sandbox Code Playgroud)

嗯,这就是我想到的...直到现在......所以,请你能给出有用的想法吗?我怎么能等待用户输入(我想过Events,但我不知道如何在这里实现它,我认为它会使代码更慢,如果我必须在每次执行代码时都要听一个键进入......

那么,有什么想法或意见吗?


更新:我想我本来应该更好地描述这个问题.你给我的所有解决方案都可以解决我提出的这个问题,但我认为我对我真正的问题并不完全可靠.我不知道是否应该问另一个问题或者继续这个问题......

Mar*_*ius 6

您可以从单独的线程运行此方法,并在按下键时设置停止变量:

object myLock = new object();
bool stopProcessing = false;

public Double? Run(int n)
{
    int i = 0;
    while (i < n)
    {
        lock(myLock)
        {
            if(stopProcessing)
                break;
        }
        // here goes the heavy computation thing
        // and I need to read some "inputkey" as well to break this loop
        i++;
    }
}
Run Code Online (Sandbox Code Playgroud)

当按下某个键时,相应地更新stopProcessing:

Console.ReadKey();
lock(myLock)
{
    stopProcessing = true;
}
Run Code Online (Sandbox Code Playgroud)


Bra*_*olt 5

如果您只是想停止应用程序,命令行中的Ctrl-C将执行此操作.如果您确实需要在长时间运行的过程中拦截输入,您可能希望生成一个工作线程来执行长时间运行的进程,然后只使用主线程与控制台进行交互(即Console.ReadLine()).