如何在C#的控制台应用程序中使用键盘输入停止正在运行的方法? [英] How to stop a running method with keyboard input in a Console Application on C#?
问题描述
简而言之,我正在利用C#进行科学计算,并且编写了一种具有while循环的方法,该方法可能会运行到用户指定的步骤数量...实际上,此方法可能需要太长时间才能执行(例如超过5小时)。当花费这么长时间时,例如,我可能想停止按 Esc 键的方法。
In short, I'm utilizing C# to scientific computation and I've written a method that has a while loop that may run to a user-specified quantity of steps... Actually, this method may take too long to execute (like more than 5 hours). When it takes this long, I may want to stop the method pressing Esc key, for example.
当我读到有关破坏<$的信息时c $ c>而时,它就像 Boolean
标志或类似的东西一样简单。所以我想这样的事情:
As I read something about breaking while
, it is as simple as a Boolean
flag or something like this. So I thought in something like this:
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
}
好吧,这是我一直想知道的...所以,请问您能在这个程度上给出有用的想法吗?我该如何等待用户输入(我想到了 Events
,但是我不确定如何在此处实现它,并且我认为这会使代码变慢,如果我每隔一段时间都要听一个键,代码就会进入...
Well, this is what I wondered until now... So please, could you give useful ideas to this extent? How can I wait for a user input (I thought about Events
, but I'm not sure how to implement it here and I think that it will make the code even slower, if I have to listen to a key at every while step the code goes into...
那么,有什么想法或意见吗?
Well, any ideas or comments?
更新:我认为我应该更好地描述这个问题。您给我的所有解决方案都可以解决我提出的这个问题,但是我认为我对自己的实际问题并不完全可靠。我不知道该问另一个问题还是继续解决这个问题...
Update: I think I should have had described better the problem. All the solutions you gave me may solve this problem I proposed, but I think I was not completely reliable to my real problem. I don't know if I should ask another question or keep with this one...
推荐答案
您可以从单独的线程运行此方法,并在按下键时设置停止变量:
You could run this method from a separate thread and set a stop variable when a key is pressed:
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++;
}
}
,当按下一个键时,相应地更新stopProcessing:
and when a key is pressed, update stopProcessing accordingly:
Console.ReadKey();
lock(myLock)
{
stopProcessing = true;
}
这篇关于如何在C#的控制台应用程序中使用键盘输入停止正在运行的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!