Pages

Tuesday, July 7, 2009

Pass parameters to the timer in C#

These days I am using C# to develop the timer component running as a windows service, which runs automatically in a specific interval.

In C#, there are 3 kinds of timer type definitions:

1. System.Windows.Forms.Timer
2. System.Threading.Timer
3. System.Timers.Timer

In my project, I choose to use the third one: System.Timers.Timer

Here is the sample usage of this kind of timer:

System.Timers.Timer timer = new System.Timers.Timer();
timer. Interval = 10000; // set the interval as 10000 ms
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed); // set the event to execute
timer.AutoReset = true; // false: only execute once
timer.Enabled = true; // to decide if execute the event of timer specified


public void timer_Elapsed(object sender, EventArgs e)
{

}

From the above sample, we know it is quite easy to use it.

Next, I have a problem if I need pass some parameters to be used in the timer event defined above: timer_Elapsed(…). The two input parameters of this event interface are fixed, you can’t add more in.

There is a tricky to achieve it. Since we can’t add more input parameters in this event, we can set the parameters into the unused property of that sender object. This way is simple, but not good.

After researching, i find a better way to deal with it: creating a new timer to extend the system timer , and then defining the additional parameters inside this new timer.

Here are the sample codes:

// define a class to extend the timer,
// then define those additional parameters to be used in the event.
// for example: add one more parameter: param1.
namespace XXX
{
public class TaskTimer : Timer
{
private string param1;

public string Param1
{
get
{
return param1;
}
set
{
param1= value;
}
}

public TaskTimer() : base()
{
}
}
}

// usage of this timer
using XXX;

TaskTimer timer = new TaskTimer();
timer.Interval = 10000;



// the event definition
public void timer_Elapsed(object sender, EventArgs e)
{
String param1 = (TaskTimer) sender).Param1;

}