0

I wrote an application that downloads files via FTP every 10 seconds and I have the following timer's code.

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

My updateLogs function:

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().

Still, after about a minute, the application freezes and the CPU usage jumps to 45+ %. When I comment out the timer3's code, the application runs fine for a long time and never crashes.

Any ideas?

Krzysiek
  • 1,487
  • 4
  • 19
  • 28

1 Answers1

5

If you are using System.Windows.Forms.Timer you should expect this kind of behavior. Although this class gives you illusion that it performs operations asynchronously, it's actually using UI thread to do actual work. For that reason, if logic executed by your timer gets stuck, your UI will too.


To alleviate this you should use timer which actually does work on a background thread, or alternatively a BackgroundWorker.

There are three Timer classes within .NET BCL.

  1. System.Windows.Forms.Timer
  2. System.Threading.Timer
  3. 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).

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. Take a look at SO question regarding this topic.

Community
  • 1
  • 1
Nikola Radosavljević
  • 6,871
  • 32
  • 44