我正在尝试使用以下代码从我的asp.net应用程序重新启动Windows时间服务,但它总是返回一个TimeoutException。我已经尝试了各种方法来删除此错误并重新启动服务,但不幸的是它失败了。我为此目的使用的代码如下所示:
private ServiceController service = new ServiceController( "W32Time", Environment.MachineName );
private TimeSpan timeout = TimeSpan.FromMilliseconds( 35000 );//15000 was the old value
// Restart W32Time Service
private void RestartService( )
{
try
{
// Stop service if it is running
if( service.Status == ServiceControllerStatus.Running )
{
service.Stop( );
service.WaitForStatus( ServiceControllerStatus.Stopped, timeout );
}
// Start service if it is stopped
if( service.Status == ServiceControllerStatus.Stopped )
{
if (!(service.Status.Equals(ServiceControllerStatus.Stopped) || service.Status.Equals(ServiceControllerStatus.StopPending)))
{
service.Stop();
}
service.Start( );
service.WaitForStatus( ServiceControllerStatus.Running, timeout );
}
}
catch( Exception ex )
{
log.Error( "Error in restarting windows service.", ex );
}
}
我使用的是Windows 7.任何人都可以建议我解决这个问题吗?任何帮助将不胜感激。
答案 0 :(得分:1)
Davids评论具有相关性,您还必须检查W32time服务的依赖性。可能不存在任何?但如果确实如此,它可能会导致你的问题。如果是64位机器,我会检查“W32 ..”
的相关性[编辑] 我附上一些代码示例,至少可以在另一台Windows 7计算机上运行。您上面提供的代码也适用于我。
class Program
{
static void Main()
{
WindowsServiceManager service = new WindowsServiceManager();
service.Run("W32Time", 2000);
service.End("W32Time", 2000);
}
}
public class WindowsServiceManager
{
internal void Run(string serviceId, int timeOut)
{
using (ServiceController serviceController = new ServiceController(serviceId))
{
TimeSpan t = TimeSpan.FromMilliseconds(timeOut);
serviceController.Start();
serviceController.WaitForStatus(ServiceControllerStatus.Running, t);
}
}
internal void End(string serviceId, int timeOut)
{
using (ServiceController serviceController = new ServiceController(serviceId))
{
TimeSpan t = TimeSpan.FromMilliseconds(timeOut);
serviceController.Stop();
serviceController.WaitForStatus(ServiceControllerStatus.Stopped, t);
}
}
}