如何实现C#启动Windows服务及关闭
如何实现C#启动Windows服务及关闭,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
为大东等地区用户提供了全套网页设计制作服务,及大东网站建设行业解决方案。主营业务为网站建设、成都网站制作、大东网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!
C#启动Windows服务及关闭实例实现的步骤和使用调用的类是什么呢?让我们来看看具体的实现:
C# 控制Windows服务的启动与关闭
// ...... using System.ServiceProcess; // ...... ////// Restart windows service /// /// ///the windows service display name ///If the restart successfully ///return true else return false public static bool RestartWindowsService(string serviceName) { bool bResult = false; try { try { //C#启动Windows服务及关闭 StopWindowsService(serviceName); Thread.Sleep(1000); } catch (Exception ex) { StartWindowsService(serviceName); Thread.Sleep(1000); StopWindowsService(serviceName); Thread.Sleep(1000); Console.WriteLine(ex.Message); } try { StartWindowsService(serviceName); Thread.Sleep(1000); } catch (Exception ex) //C#启动Windows服务及关闭{ StopWindowsService(serviceName); Thread.Sleep(1000); StartWindowsService(serviceName); Thread.Sleep(1000); Console.WriteLine(ex.Message); } bResult = true; } catch (Exception ex) { bResult = false; throw ex; } return bResult; } //C#启动Windows服务及关闭////// Start windows service /// /// ///the windows service display name ///If the start successfully ///return true else return false public static bool StopWindowsService(string serviceName) { ServiceController[] scs = ServiceController.GetServices(); bool bResult = false; foreach (ServiceController sc in scs) { if (sc.DisplayName == serviceName) { try { sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30)); sc.Stop(); bResult = true; } catch (Exception ex) { bResult = false; throw ex; } } } return bResult; } //C#启动Windows服务及关闭////// Stop windows service /// /// the windows ///service display name ///If the stop successfully ///return true else return false public static bool StartWindowsService( string serviceName) { ServiceController[] scs = ServiceController.GetServices(); bool bResult = false; foreach (ServiceController sc in scs) { if (sc.DisplayName == serviceName) { try { sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30)); sc.Start(); bResult = true; } catch (Exception ex) { bResult = false; throw ex; } } //C#启动Windows服务及关闭 } return bResult; }
C#启动Windows服务及关闭具体实现就向你介绍到这里,希望对你了解和学习C#启动Windows服务及关闭有所帮助。
看完上述内容,你们掌握如何实现C#启动Windows服务及关闭的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
当前标题:如何实现C#启动Windows服务及关闭
URL标题:http://azwzsj.com/article/gpeisp.html