4

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.

ErocM
  • 4,505
  • 24
  • 94
  • 161

1 Answers1

4

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);
      }
   }
}
LVBen
  • 2,041
  • 13
  • 27
  • Because I did this with a console application. I have the main thread sleep until all of the timers have completed to show that it works correctly. If I removed that, the application would exit before the timers had a chance to fire. – LVBen Jun 22 '14 at 01:22
  • Ah makes sense! Thanks for the help! Worked great! – ErocM Jun 22 '14 at 02:16