Wednesday, October 26, 2011

Using timers in Windows Phone 7 Applications

Some of the folks that i interacted with recently asked me how to have functionality in windows phone applications which will repeat after a particular period of time.

The answer is pretty simple - We can use "Timers" concept in Windows Phone Applications. System.Threading has Timer class which can be used to create periodically repeating tasks!

In this post, i will create a very simple application in which the end user will be intimated with the Current Date Time in form of message box after every 5 seconds. We will use the Timer class to accomplish this!

Step 1 -

In the Page Load event of the page, add the following line of code -

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) {

Timer timer = new Timer(this.TellTime, null, 1000, 5000);

}

We have simply created an instance of type System.Threading.Timer class and it has 4 parameters -
1. TimerCallback delegate - This points to the method which will be called after periodic intervals. Whatever logic or business rule you want to execute after periodic interval should be kept in this method.
2. State - It is of type System.Object and it is the input parameter pointed by TimerCallback delegate.
3. DueTime - It is in milliseconds and it is the duration after which the first invocation of callback takes place.
4.Period - It is in milliseconds and this is the amout of time to delay before the callback is invoked.

So, the above piece of code means that the method "TellTime" will be called after an initial delay of 1 second and will be periodically called after 5 seconds. We are passing no parameter to TellTime method.

Add the method TellTime to the class -


public void TellTime(object stateInfo) {

Dispatcher.BeginInvoke( () => MessageBox.Show("Date Time is :" + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString()));

}
As shown in the above piece of code, a message box will be shown to the end user displaying the current date and time after every 5 seconds.

But how will you stop the timer once the task is finished - You need to somehow set a flag that will determine whether the timer should run or stop. For accomplishing this task, use "AutoResetEvent" class in the following manner -

namespace TimersUsage {

public partial class MainPage : PhoneApplicationPage {

private int count;

AutoResetEvent autoEvent;

// Constructor

public MainPage() {

InitializeComponent();

count = 0;

}

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) {

autoEvent = new AutoResetEvent(false);

Timer timer = new Timer(this.TellTime, autoEvent,1000,5000);

autoEvent.WaitOne();

MessageBox.Show("End of timer, signal has been set");

timer.Dispose();

}

public void TellTime(object stateInfo) {

AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;

count++;

if (count >= 2) {

autoEvent.Set();

}

}

}

}

As shown in the code, after the code in TellTime method is run for 2 times, the flag will be set via autoEvent.Set method.
The autoEvent.WaitOne() method will stop the current thread execution until the flag is set via autoEvent.Set method. Once the flag is set, a message box will be shown to the end user , the timer object will be disposed and the code within TellTime method will not be called.

No comments:

Post a Comment