Question

Hye there I am new to C# and just want to run a timer manually! So i just want to know what I am doing wrong in my code. I just need to display a simple message inside my timer! my code is:

public partial class Form1 : Form
{
    System.Timers.Timer time;

    public Form1()
    {
        InitializeComponent();
        time = new System.Timers.Timer();
        time.Interval = 10;
        time.Enabled = true;
        time.Start();
    }

    private void time_Tick(object e, EventArgs ea)
    {
        for (int i = 0; i < 100; i++)
        {
            Console.WriteLine(i);
        }
    }
}

Please let me know if i am doing something wrong Thanks in advance!

Was it helpful?

Solution

You forgot to listen to the Elapsed event. Add:

time.Elapsed += new ElapsedEventHandler(time_Tick); 

To the initialisation of the timer and it should call the callback function when the timer have elapsed (at the moment 10ms)

Note also that the callback function will be called every 10 ms.
Add time.Stop(); inside the callback function if you wish it to stop run.

OTHER TIPS

Edited:

Maybe it is better to use class System.Windows.Forms.Timer instead of System.Timers.Timer. There you can call your function and also access your Textbox.

Otherwise you will receive an InvalidOperationException by trying to access your Textbox txt in time_Tick.

You don't neet a loop for incrementing your value i. just restart your timer and set the new value. What you are doing now is waiting ONE tick (lasting 1000 ms) and then starting your loop.

For example this could be your method:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
  public partial class Form1 : Form
  {
    private int i = 0;
    private Timer time;
    public Form1()
    {
        InitializeComponent();
        time = new Timer();
        time.Tick += time_Tick;
        time.Interval = 1000;
        time.Start();
    }

    private void time_Tick(object e, EventArgs ea)
    {
        if (i < 100)
        {
            txt.Text = i.ToString();
            i++;
            time.Start();
        }

    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top