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;

}

3 comments:

Prashanth said...

Nice Article.. Helped me lot.. Thanks

kgn said...

If you don't need server-based timers like the one you used in your projects one might go with "System.Windows.Forms.Timer" and use the tag-Member to pass Strings or an array of strings.

Like this: (Maxscript with .Net)

t2 = dotNetObject "System.Windows.Forms.Timer"
str = #((frameint as string), (st as string), (en as string), (nth as string))

t2.tag = str

-kgn.

Marian Zagoruiko said...

Thank you. Nice solution. Helped me a lot.