当前位置: 首页 > 编程语言 > C#

C#WindowsService-Theserviceisnotresponding开始分享

时间:2023-04-10 22:19:55 C#

C#WindowsService:TheserviceisnotrespondingStart这是我第一次尝试创建调用多线程的Windows服务。我所做的是创建一个控制台应用程序,然后添加一个Windows服务和安装程序。我的代码如下。部分类Service1:ServiceBase{publicService1(){InitializeComponent();}protectedoverridevoidOnStart(string[]args){System.Timers.Timertimer1=newSystem.Timers.Timer();timer1.Interval=10000;timer1.开始();timer1.Elapsed+=newElapsedEventHandler(timer1_Elapsed);}publicstaticvoidtimer1_Elapsed(objectsender,EventArgse){Program.ThreadController();}protectedoverridevoidOnStop(){//TODO:在此处添加代码以执行停止服务所需的任何拆卸。}}classProgram{staticvoidMain(string[]args){ThreadController();}publicstaticvoidThreadController(){for(inti=0;i{processEventLogTesting();});}}publicstaticvoidprocessEventLogTesting(){EventLog.WriteEntry("ProcessThread1","Process1Works");我不知道为什么我会收到这个错误,任何提示都会很棒。谢谢。首先,我添加了一些调试功能。这实际上很容易(当你知道怎么做时!!!)。将此添加到您的班级:[DllImport("kernel32.dll")]publicstaticexternInt32AllocConsole();然后将其添加到您的主要功能(如果您启用服务以按顺序访问UI,那么您也可以在作为服务运行时执行此操作)。for(intloop=0;loop这为您提供了一个控制台窗口,您可以使用Console.WriteLine立即将输出发送到该窗口。很好。现在您想要实现的是服务控制管理器调用您的OnStart方法,然后该方法必须返回一个OK信号,让SCM知道您的应用程序启动正常。否则,SCM认为出现问题并终止您的应用程序。因此OnStart应该启动您的线程。因此,创建一个由您的线程(和Main)运行的线程Run()方法并使OnStart尽快返回。我注意到您在代码示例中看不到任何这些:System.ServiceProcess.ServiceBase[]ServicesToRun;ServicesToRun=newSystem.ServiceProcess.ServiceBase[]{newWinService1()};System.ServiceProcess.ServiceBase.Run(ServicesToRun);我怀疑您的应用程序没有向SCM报告它已成功启动可执行文件中的“服务”。您希望您的应用程序启动,移交“服务”到SCM并让它知道你没问题,然后返回,你的服务现在在它自己的线程中运行。有关详细信息,请参阅本文:http://msdn.microsoft.com/en-us/library/aa984464(v=vs.71).aspx您在processEventLogTesting()中有无限递归。这就是它不响应的原因。当我用定时器编写Windows服务时,我所做的就是连接回调并在OnStart中启动定时器。然后我坐下来让它做它的事情。你试图在启动时做太多事情。部分类Service1:ServiceBase{privateProgramprogram;publicService1(){InitializeComponent();程序=新程序();}protectedoverridevoidOnStart(string[]args){program.Start();}protectedoverridevoidOnStop(){program.Stop();}}classProgram{privateSystems.Timers.Timer定时器;publicProgram(){timer=newSystem.Timers.Timer();定时器.间隔=10000;timer.Elapsed+=newElapsedEventHandler(timer_Elapsed);}publicvoidStart(){timer.Enabled=true;}publicvoidStop(){timer.Enabled=false;}publicstaticvoidtimer_Elapsed(objectsender,EventArgse){EventLog.WriteEntry("ProcessThread1","Process1Works");您没有在代码中启动线程,因此:for(inti=0;i{processEventLogTesting();}){IsBackground=true}.Start();在您的processEventLogTesting()中,除了错误的递归调用之外,您还创建了一个计时器,然后通过timer1=newSystem.Timers.Timer();覆盖它;timer1=newSystem.Timers.Timer();所以它不会开火。publicstaticvoidprocessEventLogTesting(){System.Timers.Timertimer1=newSystem.Timers.Timer();timer1.Interval=10000;timer1.Elapsed+=newElapsedEventHandler(timer1_Elapsed);timer1.开始();众所周知,Windows服务很难调试。如果您没有收到任何其他消息,请尝试在onstart上挂起,您应该可以附加到它,然后看看有什么问题。Nik在这里有答案,但这可能对其他Windows服务有用!以上就是C#学习教程:C#Windows服务:服务没有响应我开始分享的所有内容。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注---本文来自网络收集,不代表立场,如涉及侵权,敬请谅解点击右侧联系管理员删除。如需转载请注明出处: