Search
Sponsor
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Codes Author
Tue, 25-Nov-2014 Authors
Vishal@Neeraj
320
All Time Authors
Satyapriyanayak
12160
Vishal@Neeraj
10640
Jayakumars
8120

Latest members | More ...


(Statistics delayed by 5 minutes)
 Codes

Working With TimerCallback Delegate

Abhisek
Posted by Abhisek under C# on 11/25/2009 11:43:43 PM | Views : 5856 | Status : [Member]

Working With TimerCallback Delegate:-
***************************************



Many application have the need to call a specific method during regular intervals. For such situations we can use the System.Threading.Timer type in conjunction with a related delegate named TimerCallback .

See the following console application that will print the current time every second until the user presses a key to terminate the application.

using System;

using System.Threading;

namespace TimerApp
{
class TimerApp
{
static void PrintTime(object state)
{
Console.WriteLine("Time is: {0}, Parameter is: {1}",
DateTime.Now.ToLongTimeString(), state.ToString());
}

static void Main(string[] args)
{
Console.WriteLine("##### Working with TimerCallback #####\n")
// Create the delegate for the Timer type.
TimerCallback timeCB = new TimerCallback(PrintTime);

// Establish timer settings.
Timer t = new Timer(
timeCB, // The TimerCallback delegate type.
"Hi, Thanks", // Any info to pass into the called method.
0, // Amount of time to wait before starting.
1000); // Interval of time between calls.

Console.WriteLine("Press any key to terminate...");
Console.ReadLine();
}
}
}


DESCRIPTION:-

First we are writing the method that will contain the method to be called by the Timer type.

static void PrintTime(object state)

{
Console.WriteLine("Time is: {0}, Parameter is: {1}",
DateTime.Now.ToLongTimeString(), state.ToString());
}


This method contains only one parameter of type System.Object and its return type is void. We have to write void as we have to follow the signature of the TimerCallback delegate. As the parameter is System.Object, we can also pass multiple arguments using a System.Array or in custom way.

Then we are creating the instance of TimerCallback and passing the PrintTime() method to it to point. Then we are passing the instance to the Timer object.

Timer t = new Timer(timeCB, "Hi, Thanks", 0, 1000);//timeCB is the TimerCallback instance  



We are also passing optional arguments to the Timer constructor such as, Any info to pass into the called method, Amount of time to wait before starting, Interval of time between calls(in miliseconds).

The PrintTime() will be called every second by the Timer constructor and the information "Hi, Thanks" will be displayed every second with the time.


Abhisek Panda
Found interesting? Add this to:



Comments or Responses


Login to post response