您的位置:首页 > 其它

windows服务的停止和开启

2011-07-15 09:57 246 查看
/// <summary>
/// WindowsServiceManage
/// </summary>
public class WindowsServiceManage
{
/// <summary>
/// 重启服务
/// </summary>
/// <param name="serviceName"></param>
/// <returns></returns>
public static bool RestartWindowsService(string serviceName)
{
bool bResult = false;
try
{
try
{
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;
}

/// <summary>
/// 停止服务
/// </summary>
/// <param name="serviceName">服务名称</param>
/// <returns></returns>
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;
}

/// <summary>
/// 启动服务
/// </summary>
/// <param name="serviceName">服务名称</param>
/// <returns></returns>
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;
}
}
}
return bResult;
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: