等待一段时间,不阻塞主线程
我希望我的方法等待大约 500 毫秒,然后检查某些标志是否已更改。如何在不阻止我的应用程序的其余部分的情况下完成此操作?
I wish my method to wait about 500 ms and then check if some flag has changed. How to complete this without blocking the rest of my application?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以使用
await Task.Delay(500);
,而不会像Sleep
那样阻塞线程,并且代码比 Timer 少得多。You can use
await Task.Delay(500);
without blocking the thread likeSleep
does, and with a lot less code than a Timer.Thread.Sleep(500)
将强制当前线程等待 500 毫秒。它可以工作,但如果您的整个应用程序在一个线程上运行,则这不是您想要的。在这种情况下,您需要使用
Timer
,如下所示:如果您希望计时器重复自己。
Thread.Sleep(500)
will force the current thread to wait 500ms. It works, but it's not what you want if your entire application is running on one thread.In that case, you'll want to use a
Timer
, like so:You can set
AutoReset
to true (or not set it at all) if you want the timer to repeat itself.我不太明白这个问题。
如果您想在检查之前阻塞,请使用 Thread.Sleep(500);
如果您想每 x 秒异步检查一次,您可以使用
Timer
每 x 毫秒执行一次处理程序。这不会阻塞您当前的线程。
I don't really understand the question.
If you want to block before checking, use
Thread.Sleep(500);
If you want to check asynchronously every x seconds, you can use a
Timer
to execute a handler every x milliseconds.This will not block your current thread.
如果相关方法与应用程序的其余部分在不同的线程上执行,则执行以下操作:
If the method in question is executing on a different thread than the rest of your application, then do the following:
更新
这不会阻塞应用程序的其余部分,只会阻塞正在运行您的方法的线程。
Update
This won't block the rest of your application, just the thread that is running your method.
我最近一直在努力解决同样的问题,我需要按计划运行一个操作而不阻塞用户界面。
这是我的解决方案:
I've recently been struggling with the same issue where I needed an action to be run on schedule without blocking the UI.
Here's my solution:
使用计时器应该可以解决问题,这是一个示例
如果您需要使用线程,那么
Using a timer should do the trick
if you need to use a thread then here is an example
异步任务:
Asynchron Task:
在 WinForms 应用程序中,当我想在主线程上等待而不阻塞应用程序时,我通常使用
In a WinForms application, when I want to wait on the main thread without blocking the app, I usually use