John Reabon
John Reabon

Reputation: 61

My C# Timer code does not work

I coded a simple timer to run every 15 seconds, to broadcast some message. However, nothing happens.

  public void InitTimer()
        {
            loginTimer = new Timer();
            loginTimer.Tick += new EventHandler(loginTimer_Tick);
            loginTimer.Interval = 15000;
            loginTimer.Start();
        }

        private void loginTimer_Tick(object sender, EventArgs e)
        {
            Debug.WriteLine("Test!");
        }

This is my code.

I call the following when the button is clicked:

InitTimer();

But nothing happens every 15 seconds.. why is that?

Thanks!

Upvotes: 0

Views: 270

Answers (2)

Pierre-Luc Pineault
Pierre-Luc Pineault

Reputation: 9191

The code works fine. But nothing happens every 15 seconds.. why is that? Well, stuff happens, but you can't see it. Why? Because you are using Debug.WriteLine.

Unlike Console.WriteLine, Debug outputs to a TraceListener, not the Console. In order to see the output, you need to register a listener (which I'm sure you didn't).

So to verify if your code is really working, register a listener, use an other way (like Console.WriteLine or MessageBox.Show) or just set a breakpoint in your loginTimer_Tick method.

To register a listener and output to the Console, you can proceed like this :

TextWriterTraceListener listener = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(listener); 

Just be sure you are in Debug mode (or that you defined manually the debug flag).

As a side note, your delegate constructor call is redundant, you can shorten it to

loginTimer.Tick += loginTimer_Tick;

Upvotes: 3

Maxim Zhukov
Maxim Zhukov

Reputation: 10140

I did everything you said and didn't have any problem:

public partial class Form1 : Form
{
    Timer loginTimer;

    public Form1()
    {
        InitializeComponent();
    }

    public void InitTimer()
    {
        loginTimer = new Timer();
        loginTimer.Tick += new EventHandler(loginTimer_Tick);
        loginTimer.Interval = 1000;
        loginTimer.Start();
    }

    private void loginTimer_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("Test!");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        InitTimer();
    }
}

enter image description here Show us your code or find an error anywhere else.

Upvotes: 4

Related Questions