2011-04-13 29 views
0

我想從我的asp.net應用程序使用下面的代碼重新啓動Windows時間服務,但它總是返回一個TimeoutException。我嘗試過各種方法來刪除這個錯誤並重新啓動服務,但不幸的是它失敗了。我用於此目的代碼如下所示:無法從我的ASP.NET應用程序重新啓動Windows服務

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.任何人都可以爲我提供這個問題的解決方案嗎?任何幫助將不勝感激。

+4

應用程序運行的帳戶是否具有訪問服務的權限? – Davidann 2011-04-13 15:37:32

回答

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

該名稱在64位上仍然是W32Time。順便說一下*默認* W32Time沒有依賴關係。 – 2011-04-13 17:02:17

+1

@Mark你在那裏得到了積分,我沒有處於從我的Android系統中檢查的模式。在某些情況下,這些是完全合法的問題描述情況。我會說我成功地嘗試了W32Time。服務完全可以**手動**啓動和停止(通過服務對話框)?你可以用.NET控制其他事件嗎?它也似乎W32Time作爲本地服務運行,這將使我嘗試省略第二個參數'Environment.MachineName',使類實例化找到該帳戶本身(http://tinyurl.com/6xlktbr,msdn)。 – Independent 2011-04-13 18:38:45

+0

感謝喬納斯爲您的答案即使在手動重新啓動我的Windows時間服務,所以在諮詢我們的網絡管理員後,我的問題是存在的,我已經到達解決方案,我發佈的代碼工作正常,在我們的域外的計算機上,所以問題是我的帳戶授權。謝謝你的幫助。 – 2011-04-14 08:16:45

相關問題