如何在LAN断开连接并重新连接时使用C#重新启动服务 [英] How to restart a service using C# when lan is disconnected and connected back
本文介绍了如何在LAN断开连接并重新连接时使用C#重新启动服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好我正在尝试执行一个c#程序,该程序应该在拔下lan电缆并重新插入系统时重新启动服务。请帮帮我。
我的尝试:
我有尝试重新启动服务一段时间,但我需要它,当一个局域网被拔掉并插入后面。
Hi i am trying to execute a c# program which should restart a service when a lan cable is unplugged and plugged back to system. Please help me.
What I have tried:
I have tried restarting the service for a certain time period, but i need it when a lan is unplugged and plugged in back.
public static void RestartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
推荐答案
你可以监控NetworkChange.NetworkAvailabilityChanged Event(System.Net.NetworkInformation) [ ^ ]以便对更改作出反应。
但是,我必须说,单独的程序以这种方式重启服务听起来很奇怪。在大多数情况下,我认为服务应该自动处理这种情况。
You could monitor NetworkChange.NetworkAvailabilityChanged Event (System.Net.NetworkInformation)[^] in order to react upon changes.
However, I must say that it sounds odd that a separate program restarts the service this way. In most situations I believe that the service should autonomously handle the situation.
这篇关于如何在LAN断开连接并重新连接时使用C#重新启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文