1

how to start a forms.timer inside a simple thread,i have a problem where i need to start a timer inside a thread,how can i do that

H H
  • 263,252
  • 30
  • 330
  • 514
user158182
  • 97
  • 1
  • 9

3 Answers3

2

A better alternative would be to use the System.Timers.Timer class that doesn't need a message loop and look like the Windows forms one or you could directly use System.Threading.Timer (If you need to know all the differences between the two classes there is a blog post with all the details) :

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        using (new Timer(state => Console.WriteLine(state), "Hi!", 0, 5 * 1000))
        {
            Thread.Sleep(60 * 1000);
        }
    }
}

If you really want a System.Windows.Forms.Timer to work it need a message loop, you could start one in a thread using Application.Run either the parameter-less one or the one taking an ApplicationContext for better lifetime control.

using System;
using System.Windows.Forms;

class Program
{
    static void Main()
    {
        var timer = new Timer();
        var startTime = DateTime.Now;
        timer.Interval = 5000;
        timer.Tick += (s, e) =>
        {
            Console.WriteLine("Hi!");
            if (DateTime.Now - startTime > new TimeSpan(0, 1, 0))
            {
                Application.Exit();
            }
        };
        timer.Start();
        Application.Run();
    }
}
Julien Roncaglia
  • 17,397
  • 4
  • 57
  • 75
0

When you use threading you really want to use System.Threading.Timer.

See this question for more details: Is there a timer class in C# that isn't in the Windows.Forms namespace?

Community
  • 1
  • 1
Grzenio
  • 35,875
  • 47
  • 158
  • 240
0

The documentation says:

This timer is optimized for use in Windows Forms applications and must be used in a window.

Use something like Thread.Sleep instead.

arneeiri
  • 224
  • 1
  • 5