我什么时候知道调用 DoEvents?
如果我循环执行一个长时间的操作(例如,处理文件)并且我想更新进度条,我需要使用 DoEvents,据我所知。
但是在函数的每个循环期间调用它只会导致进度条的动画播放得非常快(或慢,具体取决于操作)。据我所知,这是因为 DoEvents 允许进度条“呼吸”,因为缺乏更好的词,导致它和表单的其余部分刷新。
我的问题是,您如何知道调用 DoEvents 是否合适?显然,你不能随心所欲地调用它——无论你经常想调用它——这会导致零星的动画等等。那么是否有一些快速方法来检查表单/应用程序是否需要调用 DoEvents?
If I'm looping through a prolonged operation (say, processing files) and I want to update a progress bar, I need to use DoEvents, from what I can understand.
But calling it during every loop of the function only results in the progress bar's animation being played back really fast (or slow, depending on the operation). I understand that this is because DoEvents allows the progress bar to "breathe", for lack of a better word, causing it and the rest of the form to refresh.
My question is, how do you know that it's appropriate to call DoEvents? Obviously you can't just call it on a whim however-often you feel like it - this results in sporadic animations, among other things. So is there some quick method to check if a form/application needs a DoEvents called?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
哦,呃——我刚刚打了自己一巴掌。
我应该只使用后台线程来处理,而不要管 UI 线程。
Oh, duh - I just smacked myself.
I should just use a background thread to process, and leave the UI thread alone.
您可以使用 BackgroundWorker。它简化了在表单上执行工作和更新控件的过程,因为您无法直接从非 UI 线程更新 UI 控件。文档中的示例更新了 Label 控件,但您可以轻松修改它以使用 ProgressBar。
Instead of messing around with threads, you can use a BackgroundWorker. It simplifies performing work and updating controls on a Form as you cannot update a UI Control directly from a non-UI thread. The example in the docs updates a Label control, but you can easily modify it to use a ProgressBar.
如果您不想摆弄线程并且不介意进行一点 Beta 测试,则 Visual Studio Async CTP 可能值得一看 - 它基本上是“DoEvents 以正确的方式完成”(以及更多)。
有关这些新异步功能的介绍,我建议查看 埃里克·利珀特的博客。
If you don't want to fiddle around with threads and you don't mind a little beta-testing, the Visual Studio Async CTP might be worth a look -- it's basically "DoEvents done the right way" (and more).
For an introduction to these new async features, I recommend to check out Eric Lippert's blog.