Posted by: Cirilo Meggiolaro | 12/2/2008

Tip of the day #49 – Executing method callbacks based on time

Tip #43 explained how to enqueue a thread to the ThreadPool. Today we are going to check how to execute a method callback based on time using the System.Threading.Timer class.

The Timer class provides 5 different overloads and all of them must receive a TimerCallback delegate as parameter. The parameters expected are:

  1. TimerCallback: A delegate to be called. It must follow the signature: MyMethod(object state);
  2. State: An object type representing an object (or null value) that will be sent to the callback;
  3. DueTime: The amount of time to wait until the callback to be called;
  4. Period: The interval between method calls.

The difference between 4 of 5 overloads is the data type expected for the DueTime and Period parameters that may accept integers, long, unsigned integers or TimeSpan as you can check below:

Timer timer = new Timer(TimerCallback);
Timer timer = new Timer(TimerCallback, object, int, int);
Timer timer = new Timer(TimerCallback, object, uint, uint);
Timer timer = new Timer(TimerCallback, object, long, long);
Timer timer = new Timer(TimerCallback, object, TimeSpan, TimeSpan);

How to…

The simplest way to work with timers to execute callback methods is showed on the following code snippet that has a static method that will be called the first time after 5 seconds and after the first run, every 2 seconds:

class Printer
{
    public static void Print(object state)
    {
        Console.WriteLine(“Received parameter: {0}”, state.ToString());
    }
}

static void Main(string[] args)
{
    Timer timer = new Timer(Printer.Print, “Text passed to the callback as a parameter.”, 5000, 2000);
    Console.Read();
}


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

Categories

%d bloggers like this: