I have to create several timers dynamically but I need the name of them when they fire.
Here is my code:
timersDict = new Dictionary<string, System.Timers.Timer>();
int i = 0;
foreach (var msg in _messages.CurrentMessages)
{
var timer = new System.Timers.Timer();
timer.Interval = int.Parse(msg.Seconds);
timer.Elapsed += Main_Tick;
timer.Site.Name = i.ToString();
i++;
}
I thought I could set it from timer.Site.Name
but I get a null exception on Site.
How do I set the name of the timer I am creating?
EDIT
I am creating this since I need to know what timer is firing when it gets to the elapsed event. I have to know what message to display once it fires.
Can I pass the message with the timer and have it display the message based on what timer it is?
Here is the rest of my code:
void Main_Tick(object sender, EventArgs e)
{
var index = int.Parse(((System.Timers.Timer)sender).Site.Name);
SubmitInput(_messages.CurrentMessages[index].MessageString);
}
I was going to use it's name to tell me which timer it was so I know what message to display since all of the timers are created dynamically.
I'd recommend wrapping the System.Timers.Timer class and add your own name field.
Here is an example:
using System;
using System.Collections.Generic;
using System.Threading;
namespace StackOverFlowConsole3
{
public class NamedTimer : System.Timers.Timer
{
public readonly string name;
public NamedTimer(string name)
{
this.name = name;
}
}
class Program
{
static void Main()
{
for (int i = 1; i <= 10; i++)
{
var timer = new NamedTimer(i.ToString());
timer.Interval = i * 1000;
timer.Elapsed += Main_Tick;
timer.AutoReset = false;
timer.Start();
}
Thread.Sleep(11000);
}
static void Main_Tick(object sender, EventArgs args)
{
NamedTimer timer = sender as NamedTimer;
Console.WriteLine(timer.name);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With