Click here to Skip to main content
15,920,801 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to implement a timer in a class.

What I have done is

  1. I have created the timer as Timer timertimeElapse;
  2. In the constructor, I typed the following two lines
    timertimeElapse = new Timer();
         timertimeElapse.Tick += new EventHandler(timerTimeOut_Tick);
    

  3. I have made the event in the same class scope
    private void timerTimeOut_Tick(object sender, EventArgs e)
    {
    }



This is not working :( Will you please suggest a way how to use timer event in the class? (not in the form)
Posted
Updated 8-Dec-09 11:55am
v3

You need to specify a timer interval, and you also need to add a call to start the timer. Here's a sample of what you need to add:
timertimeElapse.Interval = 1000; // A 1 second timer

timertimeElapse.Start();
 
Share this answer
 
v2
Hi,
wrote:
timertimeElapse = new Timer();

Is the constructor being called on the main thread of a windows forms application? It's important that it is as the System.Windows.Forms Timer will not raise tick events unless the thread is running a message loop.

The two other timers, System.Threading.Timer and System.Timers.Timer, don't need a message loop, and you may need to use one of those.

This simple modification to your code will determine if a message loop in running on the calling thread.
System.Diagnostics.Debug.Assert(
  System.Windows.Forms.Application.MessageLoop,
  "Cannot start Forms.Timer on thread without a message loop");
timertimeElapse = new Timer();
 
Share this answer
 
You need to set the interval as mentioned before and you also need to start the timer otherwise it won't do anything.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900