2012-12-14 47 views
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(); 
      } 
+0

这是一个完整的代码吗?通常在服务构造函数或OnStart方法触发异常时发生错误,尝试在try/catch块中包含OnStart方法并记录异常...还要查看事件日志,它可能会提供有关处理的异常的一些信息 –

+0

试图使用命令安装它... – Rafael

回答

0

有几件事情要检查:

  1. 确保您已经配置了EventLog源正确(MSDN)。我对Windows service Started and stopped automatically, exception handling issue的回答在这里也可能有用。
  2. 看起来您正在使用Windows窗体计时器 - 这些需要使用UI消息泵,您不会在服务中使用该消息泵(MSDN)。您应该使用System.Threading名称空间(MSDN)中的Timer类进行调查。

特别是,你可能会发现使用System.Threading.Timer将简化你的代码很大,因为这对象将管理更多的管道的为您服务。

我也建议不要致电Thread.Abort():它可能是有害的和不可预知的,在你的情况下,它似乎并不需要使用它。见To CurrentThread.Abort or not to CurrentThread.Aborthttp://msdn.microsoft.com/en-us/library/5b50fdsz.aspx

相关问题