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
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();
}
}
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?
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.
精彩评论