.:: CODE SNIPPET ::.

"Your time is limited, so don't waste it living someone else's life"

How to create a Timer in C#


In this post, I introduce how to create a timer for repeated execution with an validate on the screen. The case is when you create an function to draw and redraw something on canvas, and you want after an interval period of time, the function is executed again. My solution is using DispatcherTimer belongs to using System.Windows.Threading class.

//dont forgetto use: using System.Windows.Threading;

private DispatcherTimer timer;
private long runTume = 0;
//then you have 
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(tick);
timer.Tick += new EventHandler(timer_Tick);
void timer_Tick(object sender, EventArgs e)
{
    //throw new NotImplementedException();
    canvas.Children.Clear();
    draw(runTime);
    runTime += tick / 10000000;
}

in this case, draw(runTime); function will draw on canvas screen.
Notice that in the timer.Interval = new TimeSpan(tick); the tick value has value of 100 nanosecond, so you should concern to adjust to fix your interval time.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: