Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if a calculation within a Timer Tick, takes longer than the Tick length?

Tags:

c#

winforms

timer

In a C# System.Windows.Forms.Timer, what would happen if the code within the timer tick took longer to calculate than the tick length?

For example, in the code below, what would happen if updating the label took longer than the interval of the tick (1 second)?

private void timerProgress_Tick( object sender, EventArgs e )
    {
        if( label.Value <= label.Maximum )
        {
            label.Value = item;
        }
        update_label();
    }

I can't seem to find any answers for this, though it seems like an obvious question.

like image 733
user2283597 Avatar asked Sep 27 '22 21:09

user2283597


1 Answers

As mentioned in the comments for the question, the System.Windows.Forms.Timer will queue the Tick events, blocking the UI thread if all Tick events take longer than the set interval.

The event will continue to calculate for as long as it needs, regardless of the interval time.

For example, if you were to make a countdown timer with a tick of one second, but have it contain calculations that take 1.3 seconds, it would be delayed. This means your count down time will be incorrect as a 30 second count down will actually last around 39 seconds, regardless of the one second Tick length.

Of course, long-running tasks should not be completed within a Timer event, as these are forced onto the UI thread, and you shouldn't be blocking that thread.

like image 179
user2283597 Avatar answered Oct 06 '22 01:10

user2283597