且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

vb.net计时器和后台工作者

更新时间:2023-11-17 17:37:58

帮自己一个忙,不要为此目的使用任何计时器-避免麻烦!

相反,请始终创建和使用处理线程.即使在您需要像执行轮询那样的情况下(它本身很糟糕,但是您可能无法更改体系结构,但是-参见下文),您也可以在该线程中循环使用Thread.Sleep来实现定期数据处理.这种架构是稳定的,基于计时器的架构则不稳定. (您是否尝试设计对情况的正确处理,当由前一个事件触发的处理程序尚未完成时,如果引发了新的计时器事件,则该线程不会有此类问题.)

要查看涉及的内容,请查看我对类似主题过去的回答的集合:
如何获取keydown事件在vb.net中的不同线程上操作 [
Do yourself a big favor and do not use any kind of timers for this purpose — stay away of trouble!

Instead, always create and use a processing thread. Even in the case you need to do the polling as you do (which is bad by itself but you probably cannot change the architecture, but — see below), you can use Thread.Sleep in this thread in a loop to implement periodic data processing. This schema is stable, the one based on a timer is not. (Did you try to design correct handling of the situation, when a new timer event is fired when the handler triggered by the previous event is not yet finished? With a thread you won''t have such problems).

To see, what''s involved, look at my collection of my past answers on similar topics:
How to get a keydown event to operate on a different thread in vb.net[^].

Maybe you still can avoid polling of the file structure. Use the class System.IO.FileSystemWatcher; it will notify to any changes in file structure you subscribe to.

—SA


看看此文章 [ ^ ].这篇文章是用c#编写的,但应该可以给您一个想法.

您可以将文件处理放入后台工作器中,然后在处理每个文件(或使用哪种逻辑)之前,您可以检查是否CancellationPending并停止了线程并向用户报告了必要的进度.
Take a look at this article[^]. The article is in c# but should give you an idea.

You can put your file processing in the background worker and before you process each file (or what ever logic you use) you could check if CancellationPending and stop the thread and also report the necessary progress to the user.