简体   繁体   中英

Unable to restart windows service from my ASP.NET application

I am trying to restart Windows Time Service from my asp.net application using the following code but it always return sa TimeoutException. I have tried various ways to remove this error and restart the service but unfortunately fails in it. The code which i am using for this purpose is shown below:

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 );
    }
}

I am using Windows 7. Can anyone suggest me a solution for this problem? Any help will be appreciated.

Your example works just fine for me with the VS built-in web server.

Which leads me think that the user which your web app run under does not have permission to start/stop services. This would either be the AppPool user or your logged in user depending on how the app is configured.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM