简体   繁体   English

C#循环过程直到用户按下一个键

[英]C# Looping A Process Over And Over Until A User Presses A Key

I have a schedule checker that needs to run until a user presses a key to make it stop. 我有一个计划检查程序,需要运行,直到用户按下一个键使其停止。

My thoughts on doing this are as follows: 我这样做的想法如下:

  1. The user starts the process 用户启动该过程
  2. Process runs every 10 seconds 进程每10秒运行一次
  3. When the process is not running, Console.ReadLine(); 当进程未运行时,Console.ReadLine(); gives the user the option to press "q" to stop the process 使用户可以选择按“q”来停止该过程

My approach would work fine except the user would have to wait however long the process takes to complete before being able to stop it. 我的方法可以正常工作,除非用户必须等待该过程完成所需的时间才能停止它。 Is there any way to simultaneously run the process while being able to take a user input? 有没有办法在能够接受用户输入的同时运行该过程?

You could run the process that does the schedule work on a separate thread. 您可以在单独的线程上运行执行调度的进程。 Then the main thread could always be responsive to the user input. 然后主线程始终可以响应用户输入。 On the other hand, if you cannot kill the other process while it is running, the end result would not be any different. 另一方面,如果你在运行时无法杀死其他进程,那么最终结果将没有任何不同。 The entire application would not be able to stop until that process completed. 在该过程完成之前,整个应用程序将无法停止。 If, though, you can kill the other process at any time, then multiple (two) threads would probably work well. 但是,如果你可以随时杀死其他进程,那么多个(两个)线程可能会运行良好。

Maybe a BackgroundWorker can help. 也许BackgroundWorker可以提供帮助。

Here is an example, that uses also cancelation. 这是一个使用取消的例子。
There is also one at MSDN . MSDN上也有一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM