user158182
user158182

Reputation: 97

timer inside a thread

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

Upvotes: 1

Views: 1552

Answers (3)

Julien Roncaglia
Julien Roncaglia

Reputation: 17837

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();
    }
}

Upvotes: 2

arneeiri
arneeiri

Reputation: 224

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.

Upvotes: 0

Grzenio
Grzenio

Reputation: 36679

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?

Upvotes: 0

Related Questions