我正在尝试开发一个适用于Windows 10(64位)的Windows服务,旨在定期将记录插入本地MS SQL Server(v.11)。
它已经安装并成功运行,但没有记录被插入。我尝试使用 System.Timers.Timer
和 System.Threading.Timer
。
我还尝试在服务启动事件上进行插入。但这也没有起作用。
下面是我的代码:
public partial class Service1 : ServiceBase
{
// System.Timers.Timer timer;
System.Threading.Timer threadTimer;
public Service1()
{
InitializeComponent();
}
//UPDATE: I checked the following method code in a console application. It works fine.
private void InsertRecord()
{
try
{
using (SqlConnection connection = new SqlConnection("Server=.;Database=TestDb; Trusted_Connection=True;"))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "Insert into .....')";
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
}
}
catch (Exception ex)
{
}
}
protected override void OnStart(string[] args)
{
InsertRecord(); //This line not executed also.
TimeSpan tsInterval = new TimeSpan(0, 2, 0); //2 minute interval.
threadTimer = new Timer(new TimerCallback(threadTimer_Elapsed)
, null, tsInterval, tsInterval);
//timer = new System.Timers.Timer();
//timer.Interval = 10000;
//timer.Elapsed += Timer_Elapsed;
//timer.Enabled = true;
//timer.Start();
}
private void threadTimer_Elapsed(object state)
{
InsertRecord();
}
//private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
//{
// InsertRecord()
//}
protected override void OnStop()
{
threadTimer.Change(Timeout.Infinite, Timeout.Infinite);
threadTimer.Dispose();
threadTimer = null;
//timer.Stop();
}
}
我在这里错过了什么?
OnStart
,则服务启动失败。请查看Windows事件日志。 - user585968