RSS

How to use DispatcherTimer in Silverlight

27 Sep
A mechanical kitchen timer

Image via Wikipedia

Here I am going to explain about DispathcerTimer class in silvelright with help of a sample applicaiton.

This class is from  System.Windows.Threading namespace, which is used to process a task at specified interval of time and at a specified priority.

DispathcherTimer has Start and Stop methods to start the timer and stop the timer.

DispatcherTimer timer=new DispatcherTimer();

Methods of DispathcherTimer

timer.Start(); // it will starts the timer.

timer.Stop();  // it will stops the timer.

Properties of DispathcherTimer

timer.Interval=TimeSpan.FromMilliseconds(500); // for every 500 milliseconds, the dispatcher timer tick event will be called and In this event you can perform your task.

find Complete code here.

In this sample application for every 500 milliseconds, I am changing(ie incrementing ) the value of the textblock, it will keep on increament till the application is running.

xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace TimerTick
{
    public partial class MainPage : UserControl
    {
        int i=0;
       DispatcherTimer timer=null;
        public MainPage ()
        {
            InitializeComponent();

            this.Loaded+=new RoutedEventHandler(MainPage_Loaded);
        }

        void  MainPage_Loaded(object sender, RoutedEventArgs e)
        {
 	        timer=new DispatcherTimer();
            timer.Interval=TimeSpan.FromMilliseconds(500);
            timer.Tick+=new EventHandler(timer_Tick);
            timer.Start();
        }

        void  timer_Tick(object sender, EventArgs e)
        {
            txttimer.Text = i.ToString();
            i++;
        } 

}

}

xaml code

<UserControl x:Class="TimerTick.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock x:Name="txttimer" Width="100" Height="30">
        
    </Grid>
</UserControl>

In above code, there is a textblock called “txttimer” , it will display the incremented integer value, which will be changed for every 500 milliseconds and no need of page refresh and the timer is started in page load event.

 
Leave a comment

Posted by on September 27, 2011 in Silverlight

 

Tags: , , , , , , ,

Leave a comment