这是我正在编写的第一个窗口服务,我需要一些帮助来编写它,我正在尝试使用单线程,以便一个线程可以启动服务,而另一个线程可以负责调用执行数据库工作的函数. 我还使用了一个计时器,所以这个服务每天只运行一次下面是我的代码
我发布这个问题的原因是每当我尝试安装此服务时,它都会抛出一个错误,说“发生致命错误”,它没有给我任何细节。
public partial class Service1 : ServiceBase
{
private DateTime _lastRun = DateTime.Now;
Thread workerThread;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
ThreadStart st = new ThreadStart(WorkerFunction);
workerThread = new Thread(st);
serviceStarted = true;
workerThread.Start();
}
protected override void OnStop()
{
// flag to tell the worker process to stop
serviceStarted = false;
// give it a little time to finish any pending work
workerThread.Join(new TimeSpan(0, 2, 0));
timer1.Enabled = false;
}
private void WorkerFunction()
{
while (serviceStarted)
{
EventLog.WriteEntry("Service working",
System.Diagnostics.EventLogEntryType.Information);
// yield
if (serviceStarted)
{
Thread.Sleep(new TimeSpan(0, 20000, 0));
}
timer1.Enabled = true;
timer1.Start();
}
// time to end the thread
Thread.CurrentThread.Abort();
}
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_lastRun.Date < DateTime.Now.Date)
{
timer1.Stop();
// does the actual work that deals with the database
}
timer1.Start();
}