none
Use multiple event handlers in a single timer or multiple timers?

    Question

  • OK, I'm trying to write a simple little Windows Form program to run a timer and keep track of the amount of time being spent on the telephone.  I figuresd while I was at it I might as well make it be able to take an input and use it as a short term alarm.   The Form has a single button that will be used as a toggle.  If the timer is running, it stops it, if it's stopped it starts it.  The timer updates a label control with elapsed minutes and seconds if it's being used as a timer.  If used as an alarm it takes the value from a NumericalUpDown control that is set to zero by default and updates the label with that value interpreted as minutes and runs a count down to zero.

     

    My question is what is the best practice way of doing something like this.  Should I create, start and stop multiple timers each with it's own private tick event handler or do I pass in an event handler method for each circumstance depending on the state of my other controls or some set flags?  If it's the former that seems fairly straight forward, but if it's the latter, what is the best way to do that? 

    I ask this because I'm pretty green at c# but I'm trying to learn.  I figured this little program would be a good way to do that, but it's a little more complex than I first thought.

     

    Thanks,

    Mark

    Friday, October 14, 2011 7:55 PM

Answers

  • If you want have multiple timers, each needs its own event. I am not sure how you will create timers, but if you want to have multiple timers at the same time, you can create an array of Timers and create a common event for all of them.

    If your times will be only one at a time, then you can use one sinlge timer and one event (when one starts, this one stops, and then another starts and so on...).

    So how to have multiple timers at ones:

    I did this example code, which uses one button to start new timer. There is a list of timers, which can be used for further statistics (if you need some). 

    I have also added a listView to keep track the times created, and there are some vital information about particular timer (name, duration and current status).

    To run this code only, you need to put on form: button, numericUpDown and listView (just add, and remane button to mine name!!)

    Then simply paste the code bellow on you code editor (just dont paste a button event, which you have to create it by your self)!

     

    Code:

            List<Timer> listOfTimers;
            public Form1()
            {
                InitializeComponent();
                listOfTimers = new List<Timer>();
    
                numericUpDown1.Minimum = 0;
                numericUpDown1.Maximum = 60000; //1 minute is max
                numericUpDown1.Value = 0; //default
    
                //creating listView for list of timers:
                listView1.Columns.Add("Timer name", 80, HorizontalAlignment.Left);
                listView1.Columns.Add("Duration", 80, HorizontalAlignment.Center);
                listView1.Columns.Add("Status", 60, HorizontalAlignment.Center);
                listView1.View = View.Details;
            }
    
            private void buttonNewTimer_Click(object sender, EventArgs e)
            {
                if (numericUpDown1.Value > 0)
                {
                    Timer t = new Timer();
                    t.Interval = (int)numericUpDown1.Value * 1000;
                    t.Tag = (int)listOfTimers.Count + 1; //1st timer will have tag 1, 2nd 2,...
                    t.Tick += new EventHandler(Timers_Tick);
    
                    //adding timer to list:
                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = "Timer" + t.Tag;
                    lvi.SubItems.Add(t.Interval / 1000 + " sec");
                    lvi.SubItems.Add("Running");
                    listView1.Items.Add(lvi);
    
                    //adding this itmer to list<T>:
                    listOfTimers.Add(t);
                    //start timer:
                    t.Start();
                    //setting numericUoDown to default:
                    numericUpDown1.Value = 0;
                }
            }
    
            private void Timers_Tick(object sender, EventArgs e)
            {
                Timer tt = sender as Timer;
                tt.Stop();
                tt.Dispose();
    
                int _tag = (int)tt.Tag;
    
                //change the start of timer in the listView:
                listView1.Items[_tag - 1].SubItems[2].Text = "Stopped";
    
                //notify user which time has elapsed:
                MessageBox.Show(String.Format("Timer {0} has elapsed.", _tag));
            }
    

    Let me know what do you think, ok?!

    bye


    Mitja
    Saturday, October 15, 2011 5:26 PM
  • Hi Mark,
    Welcome to the MSDN forum!

       [SerializableAttribute]
       [ComVisibleAttribute(true)]

       public delegate void EventHandler(
         Object sender,
         EventArgs e
       )

    EventHandler is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must supply your own custom event data type and either create a delegate where the type of the second parameter is your custom type, or use the generic EventHandler(Of TEventArgs) delegate class and substitute your custom type for the generic type parameter.

    To associate the event with the method that will handle the event, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate.

    Please refer to the following links to get more details:
    EventHandler Delegate
    http://msdn.microsoft.com/en-us/library/system.eventhandler.aspx

    Handling and Raising Events
    http://msdn.microsoft.com/en-us/library/edzehd2t.aspx

    Have a nice day!


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.


    Tuesday, October 18, 2011 2:36 AM
  • Hello cnoevil incognito,

    Yeah, I kinda understand that I have to add my handler to the timer tick event, I was just wondering what the best practice method was for using multiple event handlers with a single timer, if that is the was to do it at all. Actually, since I have not gotten a response to that question I have gone ahead and added multiple timers to my form to see how that will work. Of course, I have one interesting button click event to handle, but sans any other suggestions; that's the way I'm going with it.

     

    Mark

     

     

    in my opinion for what you do, you just need to tick the event and only a timer.
    To use multiple timer depends on the continuation, then the application should do, or you want monit, but what you mean then run the length of the conversation and at the same time run the total traffic is good and only one timer event combined.

    Regards.


    Carmelo La Monica

    Blog http://community.visual-basic.it/carmelolamonica/

    WordPress http://carmelolamonica.wordpress.com/

    Twitter  http://twitter.com/carmelolamonica

    Saturday, October 15, 2011 5:42 PM

All replies

  • Hello cnoevil incognito,

    OK, I'm trying to write a simple little Windows Form program to run a timer and keep track of the amount of time being spent on the telephone. I figuresd while I was at it I might as well make it be able to take an input and use it as a short term alarm. The Form has a single button that will be used as a toggle. If the timer is running, it stops it, if it's stopped it starts it. The timer updates a label control with elapsed minutes and seconds if it's being used as a timer. If used as an alarm it takes the value from a NumericalUpDown control that is set to zero by default and updates the label with that value interpreted as minutes and runs a count down to zero.

     

    My question is what is the best practice way of doing something like this. Should I create, start and stop multiple timers each with it's own private tick event handler or do I pass in an event handler method for each circumstance depending on the state of my other controls or some set flags? If it's the former that seems fairly straight forward, but if it's the latter, what is the best way to do that?

    I ask this because I'm pretty green at c# but I'm trying to learn. I figured this little program would be a good way to do that, but it's a little more complex than I first thought.

     

    Thanks,

    Mark

    to calculate the amount for the time spent to start the timer when the call button in this case, you declare a variable of type double and the elapsed time increases with the event timer tick.
    Declare a variable of type double for the price you need, to be multiplied with the variable of time spent.
    Declare yet another variable of type double always you need for the total amount of the cost of telephone traffic.

    This is a starting point you can begin to do and see what comes out.

    then it always depends on what you'll do, but to start is fine, one step at a time

    Regards 


    Carmelo La Monica

    Blog http://community.visual-basic.it/carmelolamonica/

    WordPress http://carmelolamonica.wordpress.com/

    Twitter  http://twitter.com/carmelolamonica

    Friday, October 14, 2011 8:03 PM
  • Yeah, I kinda understand that I have to add my handler to the timer tick event, I was just wondering what the best practice method was for using multiple event handlers with a single timer, if that is the was to do it at all.  Actually, since I have not gotten a response to that question I have gone ahead and added multiple timers to my form to see how that will work.  Of course, I have one interesting button click event to handle, but sans any other suggestions; that's the way I'm going with it.

     

    Mark

     

     

    Saturday, October 15, 2011 4:24 PM
  • If you want have multiple timers, each needs its own event. I am not sure how you will create timers, but if you want to have multiple timers at the same time, you can create an array of Timers and create a common event for all of them.

    If your times will be only one at a time, then you can use one sinlge timer and one event (when one starts, this one stops, and then another starts and so on...).

    So how to have multiple timers at ones:

    I did this example code, which uses one button to start new timer. There is a list of timers, which can be used for further statistics (if you need some). 

    I have also added a listView to keep track the times created, and there are some vital information about particular timer (name, duration and current status).

    To run this code only, you need to put on form: button, numericUpDown and listView (just add, and remane button to mine name!!)

    Then simply paste the code bellow on you code editor (just dont paste a button event, which you have to create it by your self)!

     

    Code:

            List<Timer> listOfTimers;
            public Form1()
            {
                InitializeComponent();
                listOfTimers = new List<Timer>();
    
                numericUpDown1.Minimum = 0;
                numericUpDown1.Maximum = 60000; //1 minute is max
                numericUpDown1.Value = 0; //default
    
                //creating listView for list of timers:
                listView1.Columns.Add("Timer name", 80, HorizontalAlignment.Left);
                listView1.Columns.Add("Duration", 80, HorizontalAlignment.Center);
                listView1.Columns.Add("Status", 60, HorizontalAlignment.Center);
                listView1.View = View.Details;
            }
    
            private void buttonNewTimer_Click(object sender, EventArgs e)
            {
                if (numericUpDown1.Value > 0)
                {
                    Timer t = new Timer();
                    t.Interval = (int)numericUpDown1.Value * 1000;
                    t.Tag = (int)listOfTimers.Count + 1; //1st timer will have tag 1, 2nd 2,...
                    t.Tick += new EventHandler(Timers_Tick);
    
                    //adding timer to list:
                    ListViewItem lvi = new ListViewItem();
                    lvi.Text = "Timer" + t.Tag;
                    lvi.SubItems.Add(t.Interval / 1000 + " sec");
                    lvi.SubItems.Add("Running");
                    listView1.Items.Add(lvi);
    
                    //adding this itmer to list<T>:
                    listOfTimers.Add(t);
                    //start timer:
                    t.Start();
                    //setting numericUoDown to default:
                    numericUpDown1.Value = 0;
                }
            }
    
            private void Timers_Tick(object sender, EventArgs e)
            {
                Timer tt = sender as Timer;
                tt.Stop();
                tt.Dispose();
    
                int _tag = (int)tt.Tag;
    
                //change the start of timer in the listView:
                listView1.Items[_tag - 1].SubItems[2].Text = "Stopped";
    
                //notify user which time has elapsed:
                MessageBox.Show(String.Format("Timer {0} has elapsed.", _tag));
            }
    

    Let me know what do you think, ok?!

    bye


    Mitja
    Saturday, October 15, 2011 5:26 PM
  • Hello cnoevil incognito,

    Yeah, I kinda understand that I have to add my handler to the timer tick event, I was just wondering what the best practice method was for using multiple event handlers with a single timer, if that is the was to do it at all. Actually, since I have not gotten a response to that question I have gone ahead and added multiple timers to my form to see how that will work. Of course, I have one interesting button click event to handle, but sans any other suggestions; that's the way I'm going with it.

     

    Mark

     

     

    in my opinion for what you do, you just need to tick the event and only a timer.
    To use multiple timer depends on the continuation, then the application should do, or you want monit, but what you mean then run the length of the conversation and at the same time run the total traffic is good and only one timer event combined.

    Regards.


    Carmelo La Monica

    Blog http://community.visual-basic.it/carmelolamonica/

    WordPress http://carmelolamonica.wordpress.com/

    Twitter  http://twitter.com/carmelolamonica

    Saturday, October 15, 2011 5:42 PM
  • Thanks for the code Mitja.  I find plenty of tutorials that tell you about timers but they typically illustrate some very simple concepts using a single timer with a single even handler.  I am curious if there ever is the use case for a single timer to utilize multiple event handlers in the Tick event and if so; what is the best practice method.  Do you just NULL the existing event handler in the onTick event of the timer and drop another one in.  Should you use delegates or just drop a new event handler method straight in.  Or am I off base altogether and the general case is that I should just create a new timer with it's own event handler for each and every different use case.

    How would a "real" programmer handle it?   I ask this because I am a novice and just want to know what the generally accepted practice would be for this situation.

     

    Thanks again,

    Mark

     

     

    Saturday, October 15, 2011 9:22 PM
  • Hi Mark,
    Welcome to the MSDN forum!

       [SerializableAttribute]
       [ComVisibleAttribute(true)]

       public delegate void EventHandler(
         Object sender,
         EventArgs e
       )

    EventHandler is a predefined delegate that specifically represents an event handler method for an event that does not generate data. If your event does generate data, you must supply your own custom event data type and either create a delegate where the type of the second parameter is your custom type, or use the generic EventHandler(Of TEventArgs) delegate class and substitute your custom type for the generic type parameter.

    To associate the event with the method that will handle the event, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate.

    Please refer to the following links to get more details:
    EventHandler Delegate
    http://msdn.microsoft.com/en-us/library/system.eventhandler.aspx

    Handling and Raising Events
    http://msdn.microsoft.com/en-us/library/edzehd2t.aspx

    Have a nice day!


    Yoyo Jiang[MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.


    Tuesday, October 18, 2011 2:36 AM