C# 窗口服务中出现错误
这是我正在编写的第一个窗口服务,我需要一些帮助来编写它,我正在尝试使用单线程,这样一个线程就可以启动服务 另一个线程可以负责调用执行数据库工作的函数。我还使用了一个计时器,这样这个服务每天只运行一次。下面是我的代码 我发布这个问题的原因是,每当我尝试安装这个服务时,它都会抛出一个错误,说“发生致命错误”,它不会给我任何详细信息C# 窗口服务中出现错误,c#,multithreading,windows-services,C#,Multithreading,Windows Services,这是我正在编写的第一个窗口服务,我需要一些帮助来编写它,我正在尝试使用单线程,这样一个线程就可以启动服务 另一个线程可以负责调用执行数据库工作的函数。我还使用了一个计时器,这样这个服务每天只运行一次。下面是我的代码 我发布这个问题的原因是,每当我尝试安装这个服务时,它都会抛出一个错误,说“发生致命错误”,它不会给我任何详细信息 public partial class Service1 : ServiceBase { private DateTime _lastRun =
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();
}
公共部分类Service1:ServiceBase
{
private DateTime\u lastRun=DateTime.Now;
螺纹加工螺纹;
公共服务1()
{
初始化组件();
}
启动时受保护的覆盖无效(字符串[]args)
{
ThreadStart st=新的ThreadStart(WorkerFunction);
workerThread=新线程(st);
serviceStarted=true;
workerThread.Start();
}
受保护的覆盖void OnStop()
{
//指示辅助进程停止的标志
serviceStarted=false;
//给它一点时间来完成任何悬而未决的工作
Join(新的时间跨度(0,2,0));
timer1.Enabled=false;
}
私有void WorkerFunction()
{
while(服务启动)
{
EventLog.WriteEntry(“服务工作”,
System.Diagnostics.EventLogEntryType.Information);
//屈服
如果(服务已启动)
{
睡眠(新的时间跨度(0,20000,0));
}
timer1.Enabled=true;
timer1.Start();
}
//结束线程的时间到了
Thread.CurrentThread.Abort();
}
私有无效计时器1_已过(对象发送方,System.Timers.ElapsedEventArgs e)
{
如果(_lastRun.Date
有几件事需要检查:
EventLog
源代码()。我对的回答在这里也很有用系统中使用计时器类。线程命名空间()
System.Threading.Timer
将大大简化您的代码,因为该对象将为您管理更多的管道
我还建议不要调用Thread.Abort()
:它可能有害且不可预测,在您的情况下,您似乎根本不需要使用它。请参阅和
.这是完整的代码吗?当服务构造函数或OnStart方法引发异常时,通常会发生错误,请尝试在try/catch块中包含OnStart方法并记录异常…同时查看事件日志,它可能会为您提供有关处理异常的一些信息,您正在尝试使用命令安装它。。。