locked
Dynamically adding and managing timers at runtime RRS feed

  • Question

  • I am building an app which will query data about a machine from a webservice every minute or so. There could be 1 or 15 machines, depending on what is required at the time. What I am having trouble with is dynamically creating and then managing each timer tick event. I have the code to create the timer itself but not sure how to get the tick event firing independently for each timer. Since the actual TICK event is the same for each timer (ie it just queries a web server based on a machine name) I would like to keep this as one sub. My thinking is that I might need an arraylist which adds the machinename to the tag of the timer, but not sure how to code this logically. Code below is simplified version of where I'm going at the moment, although happy to listed to better ways to write this!

           ArrayList list = new ArrayList();
            private void button1_Click(object sender, EventArgs e)
            {
                Timer t = new Timer();
                t.Tag = MachineName;
                t.Interval = 60000;
                t.Tick += tm_Tick;
                list.Add(t);
                t.Enabled = true;
                t.Start();
            }
             private void tm_Tick(object sender, EventArgs e)
            {
             //   QueryWebserver(Machinename)
            }


    • Edited by SJBond Wednesday, July 11, 2012 10:08 AM
    Wednesday, July 11, 2012 10:06 AM

Answers

  • Hi,

    You can get the MachineName from the sender timer object in your event handler:

    private void tm_Tick(object sender, EventArgs e)
            {
                QueryWebserver((sender as Timer).Tag);
            }


    • Proposed as answer by Reed Copsey, JrMVP Wednesday, July 11, 2012 3:28 PM
    • Marked as answer by SJBond Wednesday, July 11, 2012 3:49 PM
    Wednesday, July 11, 2012 10:27 AM

All replies

  • Hi,

    You can get the MachineName from the sender timer object in your event handler:

    private void tm_Tick(object sender, EventArgs e)
            {
                QueryWebserver((sender as Timer).Tag);
            }


    • Proposed as answer by Reed Copsey, JrMVP Wednesday, July 11, 2012 3:28 PM
    • Marked as answer by SJBond Wednesday, July 11, 2012 3:49 PM
    Wednesday, July 11, 2012 10:27 AM
  • Fantastic, thank you. Simple when you know how!
    Wednesday, July 11, 2012 3:48 PM