0
这是我写的第一个窗口服务,我需要一些帮助来编写它,我试图使用单个线程,以便一个线程可以启动服务 而另一个线程可以照顾调用数据库工作的函数。我也使用计时器,以便此服务每天只运行一次以下是我的代码在窗口服务中发生错误
我发布此问题的原因是每当我尝试安装此服务时,它抛出一个错误说“致命错误发生” ,它没有给我任何细节。
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();
}
这是一个完整的代码吗?通常在服务构造函数或OnStart方法触发异常时发生错误,尝试在try/catch块中包含OnStart方法并记录异常...还要查看事件日志,它可能会提供有关处理的异常的一些信息 –
试图使用命令安装它... – Rafael