简体   繁体   English

暂停计时器似乎无法正常工作

[英]Pausing timers doesn't seem to work correctly

I wrote an application that downloads files via FTP every 10 seconds and I have the following timer's code. 我编写了一个应用程序,该应用程序每10秒通过FTP下载文件,并且具有以下计时器的代码。

timer3.Tick += new EventHandler(updateLogs);
timer3.Interval = (1000) * (10);
timer3.Enabled = true;
timer3.Start();

My updateLogs function: 我的updateLogs函数:

timer3.Enabled = false;
server1_log = downloadLog("192.168.0.217", 1);
server2_log = downloadLog("192.168.0.216", 2);
server3_log = downloadLog("192.168.0.215", 3);
timer3.Enabled = true;

I realize that the requests may take longer than 10s and this is why I am disabling the timer before, and enabling after, calling downloadLog(). 我意识到请求可能花费超过10秒钟的时间,这就是为什么我在调用downloadLog()之前禁用计时器,并在之后启用计时器的原因。

Still, after about a minute, the application freezes and the CPU usage jumps to 45+ %. 仍然,大约一分钟后,应用程序冻结,CPU使用率跃升到45%以上。 When I comment out the timer3's code, the application runs fine for a long time and never crashes. 当我注释掉timer3的代码时,该应用程序可以长时间正常运行,并且绝不会崩溃。

Any ideas? 有任何想法吗?

If you are using System.Windows.Forms.Timer you should expect this kind of behavior. 如果您使用的是System.Windows.Forms.Timer ,则应该期望这种行为。 Although this class gives you illusion that it performs operations asynchronously, it's actually using UI thread to do actual work. 尽管此类给人一种错觉,即它异步执行操作,但实际上是使用UI线程来完成实际工作。 For that reason, if logic executed by your timer gets stuck, your UI will too. 因此,如果您的计时器执行的逻辑卡住了,那么您的UI也将陷入困境。


To alleviate this you should use timer which actually does work on a background thread, or alternatively a BackgroundWorker . 为了减轻这种情况,您应该使用计时器,该计时器实际上在后台线程上起作用,或者在BackgroundWorker上起作用。

There are three Timer classes within .NET BCL. .NET BCL中有三个Timer类。

  1. System.Windows.Forms.Timer System.Windows.Forms.Timer
  2. System.Threading.Timer System.Threading.Timer
  3. System.Timers.Timer System.Timers.Timer

Best fit for your needs is System.Timers.Timer (discussion about this would be rather long. For more information it's best that you read MSDN Magazine article comparing these three ). 最适合您的需求的是System.Timers.Timer (对此的讨论会相当长。有关更多信息,最好阅读《 MSDN杂志》中比较这三个文章的文章 )。

What you also need to know when doing your work asynchronously and updating UI is that you can't/shouldn't access UI directly from worker thread. 在异步执行工作和更新UI时,您还需要知道的是,您不能/不应直接从工作线程访问UI。 Take a look at SO question regarding this topic . 看一下关于这个话题的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM