且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#Windows服务错误1053:服务无法及时响应启动或控制请求。

更新时间:2022-05-14 01:12:32

不建议在服务 OnStart()事件中编写任何业务逻辑。让服务以最短的时间顺利开始。它提供更好的用户体验。如果您在 OnStart()中写入任何逻辑,那么该服务将处于开始状态,直到执行完成。

您可以做的是将所有逻辑移动到单独的方法中。然后通过传递使用新创建的方法创建的 ThreadStart 对象来创建线程

It is not recomended to write any business logic inside the service OnStart() event. Let the service start smoothly with minimum required time. It gives better user experience. If you write any logic inside OnStart() then the service will be in "Starting" state untill the execution finished.
What you can do is move all of your logic into a separate method. Then create a Thread by passing a ThreadStart object created with the newly created method.
//include namespace
using System.Threading;

//extract business logic to a new method
private void ExecuteMyBusiness()
{
   this.WriteToFile("Service started {0}");
   this.ScheduleService();
}

//your changed OnStart() event
protected override void OnStart(string[] args)
{
   Thread myBusinessThread = new Thread(new ThreadStart(ExecuteMyBusiness));
   myBusinessThread.Start();
}





你可以尝试一下,如果它工作正常那么好又好。

但是,这不是全部。你需要检查 OnStop(),如果线程还没有完成分配给它的任务的执行,那么它应该等待它完成。

为此目的,您需要加入以下更改 -



You can give this a try and if it works fine then well and good.
But, this is not all. You need to check in OnStop() for if the thread has not finished the execution of the task assigned to it then it should wait for it to complete.
For that purpose, you need to incorporate following changes-

//declare a global variable to keep track of thead execution status
private bool isThreadRunning= false;

//change the flag as per execution status
private void ExecuteMyBusiness()
{
   isThreadRunning=true;
   this.WriteToFile("Service started {0}");
   this.ScheduleService();
   isThreadRunning=false;
}

//change your OnStop() accordingly
protected override void OnStop()
{
   while(isThreadRunning)
   {
      Thread.Sleep(1000); //wait for 1 second and then try again
   }
   this.WriteToFile("Service stopped {0}");
   this.Schedular.Dispose();
}





好​​的。这就是全部吗?

不,但它应解决您当前的问题。你需要做各种验证,但这应该是一个很好的开始。



希望,它有帮助:)

请让我知道,如果您在实施此设计时遇到任何问题或疑问。



Ok. Is that all?
No, but it should resolve your current problem. You need to do various validation but this should be a good approach to start with.

Hopefully, it helps :)
Please let me know, if you have questions or problem in implementing this design.