做一个简单的定时器,每五秒向控制台打印出时间,但是经常会出现打印不了,调试台显示:线程《无名称》已退出,返回值0(0X0),在控制台随便按一下按钮则又可以显示了。请问这是怎么回事?要怎么办?是不是程序写错了。
但是有时运行又是正常的。using System;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;namespace timer
{
/// <summary>
/// main 的摘要说明。
/// </summary>
class main
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static Timer timer = new Timer(new TimerCallback(timer_show), null, 0, 5000);
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
Console.WriteLine("开始定时进行");
while(true)
{
Console.ReadLine();
timer.Dispose();
}
} static void timer_show (Object state)
{
Console.WriteLine(System.DateTime.Now.ToString()); } }
}
但是有时运行又是正常的。using System;
using System.Threading;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;namespace timer
{
/// <summary>
/// main 的摘要说明。
/// </summary>
class main
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static Timer timer = new Timer(new TimerCallback(timer_show), null, 0, 5000);
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
Console.WriteLine("开始定时进行");
while(true)
{
Console.ReadLine();
timer.Dispose();
}
} static void timer_show (Object state)
{
Console.WriteLine(System.DateTime.Now.ToString()); } }
}
加Application.DoEvents();
原因有System.Windows.Forms.Timer用于UI而且不能用于多线程,
所以如果用多线程启动时会出现无法触发Timer_Tick事件。
System.Timers.Timer可以用于多线程。
你去试试,我以前也出现了这个问题,后来发现不能用于非UI,改成System.Timers.Timer就ok了。
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
Timer timer = new Timer(new TimerCallback(timer_show), null, 0, 5000);
Console.WriteLine("开始定时进行");
while(true)
{
Console.ReadLine();
}
timer.Dispose();
}
后好象没问题,但是timer.Dispose()有警告:(无法检测到的代码)
是怎么回事啊?
应该不能得,就如我上面所说的。
代码应该改成这样,请注意由于你的while的条件一直都是true,所以你的timer.Dispose()这条语句不会被执行,所以警告"无法检测到的代码"[STAThread]
static void Main()
{
System.Timers.Timer timer = new System.Timers.Timer() ;
timer.Interval = 1000 ;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_show);
Console.WriteLine("开始定时进行");
timer.Start() ;
while(true)
{
Console.ReadLine();
timer.Dispose();
}
}static void timer_show (Object state,System.Timers.ElapsedEventArgs e)
{
Console.WriteLine(System.DateTime.Now.ToString());
}