C# 一遍又一遍地循环进程,直到用户按下某个键
我有一个时间表检查器,需要运行直到用户按下某个键使其停止。
我这样做的想法如下:
- 用户启动进程 进程
- 每 10 秒运行一次
- 当进程未运行时,Console.ReadLine();为用户提供按“q”来停止进程的选项
我的方法可以正常工作,除非用户必须等待进程完成所需的时间才能停止它。有什么方法可以在接受用户输入的同时同时运行该流程吗?
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:
- The user starts the process
- Process runs every 10 seconds
- When the process is not running, Console.ReadLine(); gives the user the option to press "q" to stop the process
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在单独的线程上运行执行计划工作的进程。这样主线程就可以始终响应用户输入。另一方面,如果您无法在另一个进程运行时终止它,那么最终结果不会有任何不同。在该过程完成之前,整个应用程序将无法停止。不过,如果您可以随时终止其他进程,那么多个(两个)线程可能会很好地工作。
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.
也许 BackgroundWorker 可以提供帮助。
这里一个例子,也使用取消。
MSDN 上也有一个。
Maybe a BackgroundWorker can help.
Here is an example, that uses also cancelation.
There is also one at MSDN.