C# 一遍又一遍地循环进程,直到用户按下某个键

发布于 2024-09-02 06:39:26 字数 229 浏览 5 评论 0原文

我有一个时间表检查器,需要运行直到用户按下某个键使其停止。

我这样做的想法如下:

  1. 用户启动进程 进程
  2. 每 10 秒运行一次
  3. 当进程未运行时,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:

  1. The user starts the process
  2. Process runs every 10 seconds
  3. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

萌无敌 2024-09-09 06:39:26

您可以在单独的线程上运行执行计划工作的进程。这样主线程就可以始终响应用户输入。另一方面,如果您无法在另一个进程运行时终止它,那么最终结果不会有任何不同。在该过程完成之前,整个应用程序将无法停止。不过,如果您可以随时终止其他进程,那么多个(两个)线程可能会很好地工作。

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.

白衬杉格子梦 2024-09-09 06:39:26

也许 BackgroundWorker 可以提供帮助。

这里一个例子,也使用取消。
MSDN 上也有一个。

Maybe a BackgroundWorker can help.

Here is an example, that uses also cancelation.
There is also one at MSDN.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文