1

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

例如:我会在应用程序配置中提到小时为“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 
 }
4

1 回答 1

4

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

于 2012-07-01T14:00:06.350 回答