服务状态显示为启动时使用c#.net时未启动的原因

时间:2012-07-01 13:44:52

标签: c# timer

这里我正在使用窗口服务,使用逻辑,因为我的服务在24小时内只能在app.config中配置的帮助下工作一次。

例如:我会在应用配置中将小时称为“10”所以每天我的服务将按正好10个时钟运行

但问题是,当我启动我的服务时,它抛出一个错误,因为1053(及时时尚错误)和状态显示为在services.msc中启动,没有更多启动和重新启动功能未显示在弹出窗口中右键单击

想知道它是完全完成了这项工作,完全是十点钟。

为什么它没有显示为已启动,为什么它会抛出错误?

我已经粘贴了示例代码,请及时告知我是否做错了

启动方法

protected override void OnStart(string[] args)
{
     DateTime tenAM = DateTime.Today.AddHours(strSETHOST);


     if (DateTime.Now > tenAM)
          tenAM = tenAM.AddDays(1);


     // calculate milliseconds until the next 10:00 AM.  
     int timeToFirstExecution = (int)tenAM.Subtract(DateTime.Now).TotalMilliseconds;

     // calculate the number of milliseconds in 24 hours.   
     int timeBetweenCalls = (int)new TimeSpan(24, 0, 0).TotalMilliseconds;

     TimerCallback methodToExecute = kickstart;

     // start the timer.  The timer will execute "ProcessFile" when the number of seconds between now and   
     // the next 10:00 AM elapse.  After that, it will execute every 24 hours.   
     System.Threading.Timer timer = new System.Threading.Timer(methodToExecute, null, timeToFirstExecution, timeBetweenCalls);

     Thread.Sleep(Timeout.Infinite);

 }

 protected override void OnStop()
 {
 }

 public static void kickstart(object nowtime)
 {

      Service1  foo = new Service1();
      foo.Startjob();
 }

 private void Startjob()
 {
      using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew)) // Transaction Scope Started
      {
           if ((threadPURGE == null) || (threadPURGE.ThreadState == System.Threading.ThreadState.Stopped) || (threadPURGE.ThreadState == System.Threading.ThreadState.Unstarted) || (threadPURGE.ThreadState == System.Threading.ThreadState.Aborted))
           {
                threadPURGE = new Thread(new ThreadStart(DynamicThreadGen));  // Thread Initialize for ITD 
           }

           try
           {
                if ((threadPURGE == null) || (threadPURGE.ThreadState == System.Threading.ThreadState.Stopped) || (threadPURGE.ThreadState == System.Threading.ThreadState.Unstarted) || (threadPURGE.ThreadState == System.Threading.ThreadState.Aborted))
                {
                     threadPURGE.Start();  // Thread Started for ITD 
                }


           }
           catch (Exception ex)
           {
                string err = ex.Message.ToString();
           }
           finally
           {
                scope.Complete();
           }
      }

 }

 private void DynamicThreadGen()
 {
     /// service work 
 }

1 个答案:

答案 0 :(得分:4)

您需要允许OnStart方法在Windows分配的超时内完成,否则Windows无法判断它是否已启动。抓住类字段中的Timer,这样就不会收集和处理垃圾,然后抛弃Thread.Sleep