creating an array of System.Windows.Forms.Timers

T

TheJediMessiah

Hi,

I have a number of objects for which I want to create a timer for.
So for each object I would like to have a timer which runs at a
different interval.

For a single timer I know how to implement

timer = new System.Windows.Forms.Timer();
timer.Tick += new EventHandler(Timer_Tick);
timer.Interval = 1000 * obj.InterleavedMessage.Time;
timer.Enabled = true;

But how can I have an array of timers for an array of objects which
will have different intervals?
For each timer I would like to call a different timer_tick handler.

Cheers
 
J

Jon Skeet [C# MVP]

TheJediMessiah said:
I have a number of objects for which I want to create a timer for.
So for each object I would like to have a timer which runs at a
different interval.

For a single timer I know how to implement

timer = new System.Windows.Forms.Timer();
timer.Tick += new EventHandler(Timer_Tick);
timer.Interval = 1000 * obj.InterleavedMessage.Time;
timer.Enabled = true;

But how can I have an array of timers for an array of objects which
will have different intervals?
For each timer I would like to call a different timer_tick handler.

Just do it the same way you would with any other array:

Timer[] timers = new Timer[someSize];

timers[0] = new Timer();
timers[0].Tick += ...;

etc

Jon
 
T

TheJediMessiah

You have not filled in the most critical part but just left it with ...

If I create an array of timers like you have suggested.

Timer[] timers = new Timer[someSize];
for(int i=0;i<someSize;i++)
{
timer.Tick += new EventHandler(Timer_Tick);
timer.Interval = 1000 * obj.InterleavedMessage.Time;
timer.Enabled = true;
}

Is this correct?
How do I know which Timer_Tick which timer object has raised it???
 
J

Jon Skeet [C# MVP]

TheJediMessiah said:
You have not filled in the most critical part but just left it with ...

Well yes - I was assuming that having filled in a couple of properties,
the way to do the rest was obvious.
If I create an array of timers like you have suggested.

Timer[] timers = new Timer[someSize];
for(int i=0;i<someSize;i++)
{
timer.Tick += new EventHandler(Timer_Tick);
timer.Interval = 1000 * obj.InterleavedMessage.Time;
timer.Enabled = true;
}

Is this correct?
Yes.

How do I know which Timer_Tick which timer object has raised it???


The first parameter to the event is the "source" which should be the
Timer generating the event.

Jon
 
T

TheJediMessiah

Thanks.
I created subclass of the Timer class and added an ID property so I
knew which timer was passed into TImer_Tick.

Thanks again for your help.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top