Click here to Skip to main content
15,904,153 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
how to use timer without Freezing FORM

What I have tried:

how to use timer without Freezing FORM
Posted
Updated 13-Jan-20 4:29am

Using a timer won't "freeze a form" unless you are doing something silly: either a very, very short Interval or a long running method in the timer Tick handler method.

Timers aren't "magic bullets" - they are events that are fed into your code at a specific interval (or at least, after the interval) so that you code can do something that needs to be done often, like update a time or countdown on the screen, reflect the cursor position on a status line, that kind of thing. And as such, it runs on the main thread, which also processes everything else for the form. If your time plus the other processing takes too long, the Paint events never "reach the front of the queue" so yoru form never updates, and in extreme cases your user clicks are never processed either.

If you want to do a long running task, even if you want it to run at a specific interval you need to move it into a background thread and update the UI only when it has results. As CPallini suggests, a BackgroundWorker is a good choice for this as it includes a mechanism to report progress / results back to the mind thread - which is the only thread that can access UI components at all!
 
Share this answer
 
You could replace the timer with, for instance, a BackgroundWorker object. See this CodeProject article: BackgroundWorker Class Sample for Beginners[^].
 
Share this answer
 
using Timer = System.Windows.Forms.Timer;

set this at top of using .

Then under class,

set

Timer timer;
DateTime startTime;


and

then call

startTime = DateTime.Now;
timer.Start();


to start the timer
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900