【问题标题】:error occured in window service窗口服务发生错误
【发布时间】:2012-12-14 22:37:08
【问题描述】:

这是我正在编写的第一个窗口服务,我需要一些帮助来编写它,我正在尝试使用单线程以便一个线程可以启动服务 另一个线程可以负责调用执行数据库工作的函数。我还使用了一个计时器,所以这个服务每天只运行一次下面是我的代码

我发布这个问题的原因是每当我尝试安装此服务时,它都会抛出一个错误,说“发生致命错误”,它没有给我任何细节。

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 方法并记录异常...还请查看事件日志,它可能会为您提供一些有关已处理异常的信息
  • 你正在尝试使用命令安装它...

标签: c# multithreading windows-services


【解决方案1】:

有几件事需要检查:

  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

【讨论】:

    猜你喜欢
    • 2010-12-19
    • 2020-10-27
    • 1970-01-01
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多