如何在 C# 中实现异步暂停?
我有一个用 C# (Visual Studio) 编写的程序,可以在托盘上运行。 我希望它每 10 分钟执行一次操作。 我现在有以下代码:
while(true)
{
Thread.Sleep(10000);
// my stuff
}
但它不起作用。它冻结了一个程序。
I have a program written in C# (Visual Studio), that works on a tray.
I want it to do one action every 10 minutes.
I have following code now:
while(true)
{
Thread.Sleep(10000);
// my stuff
}
But it doesn't work. It freezes a program.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用计时器对象而不是创建 while 循环。
You should use the timer object and not create a while loop.
Thread.Sleep 使调用线程休眠 X 时间。如果这个线程是前端线程(负责处理消息的线程),它确实会冻结应用程序,因为任何用于处理事件或重画的消息都不会被处理,直到线程再次唤醒并有机会处理消息。
您应该做的是每 10 秒安排一次此逻辑。
在表单上放置一个计时器并指定它每 10 秒运行一次。在 Tick 事件中,调用您的自定义操作。
Thread.Sleep makes the calling thead Sleep for an X ammount of time. If this thread is the frontend thread (the one responsible for handling messages), it will indeed freeze the application since any message for handling events or repainting wont be handeled untill the Thread wakes up again and gets a chance of handling the messages.
What you should do is schedule this logic every 10 seconds.
Drop a timer on your form and specify it to run each 10 seconds. Within the Tick event, call your custom action.
Thread.Sleep“停止”当前线程。如果只有一个线程,则一切都会暂停。
你想达到什么目的?
也许您需要第二个线程,或者更好的解决方案是计时器每 10 分钟触发一次操作
。 Task.StartNew() 或 线程池
Thread.Sleep "stops" the current thread. if you only have one thread, everything is paused.
What do you want to achieve ?
Perhaps you need a second thread, or perhaps the better solution a timer which triggers a action every 10 minutes
s. Task.StartNew() or ThreadPool