2015-09-28 122 views
0

我用下面的代碼安裝Windows服務:註冊Windows服務

ServiceBase.Run(new ServiceProcess(serviceName, serviceArgs)); 

documentation我明白了,這個方法也呼籲服務OnStart方法。但我想將服務安裝爲已停止並稍後手動啓動它。

+0

如果安裝後停止服務,該怎麼辦?這對你有用嗎? – Viru

+0

@Viru這是一個選項,但我擔心服務可以在停止之前執行一些操作,這對我的應用程序不利。所以我試圖找到解決方案來避免這個 – Backs

+0

雅得到它,但在這種情況下,你必須重寫onStart方法,並提供你自己的實現,你可以檢查它是否是第一次啓動,如果是的話,那麼不要調用開始 – Viru

回答

0

我研究了我們的項目,發現自定義安裝。我忽略了方法OnCommitted和檢查參數Delayed現在開始服務或稍後手工完成。

[RunInstaller(true)] 
public class CustomInstaller : System.Configuration.Install.Installer 
{ 
    public CustomInstaller() 
    { 
     _installProcess = new ServiceProcessInstaller { Account = ServiceAccount.NetworkService }; 
     _installService = new CustomServiceInstaller(typeof(ServiceImplementation)); 

     // Remove built-in EventLogInstaller: 
     _installService.Installers.Clear(); 

     Installers.Add(_installProcess); 
     Installers.Add(_installService); 
    } 

    public override void Install(IDictionary stateSaver) 
    { 
     //install 
     base.Install(stateSaver); 
    } 

    protected override void OnCommitted(IDictionary savedState) 
    { 
     var delyed = bool.Parse(GetContextParameter(@"Delayed")); 

     if (!delyed) 
     { 
      new ServiceController(GetContextParameter(ServiceNameKey)).Start(); 
     } 
    } 

    private string GetContextParameter(string parameterKey) 
    { 
     var parameterValue = Context.Parameters[parameterKey]; 
     if (string.IsNullOrWhiteSpace(parameterValue)) 
      throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, MissingRequiredParameterErrorMessage, parameterKey)); 
     return parameterValue; 
    } 
} 
0
private static InitialStartDone = false; // declared in service class 
protected Overrride void OnStart(string[] args); 
{ 
    if(!InitialStartDone) 
    { 
     InitialStartDone = true; 
    } 
    else 
    { 
     base.OnStart(args); 
    } 
} 

嘗試覆蓋上開始的默認行爲,使用靜態變量來檢測,如果它被稱爲第一次

+0

謝謝,我稍後再檢查並告訴你結果 – Backs

+0

我不認爲這會起作用。 **每次**開始服務時,InitialStartDone將爲假,因此服務永遠不會啓動! – sgmoore

+0

我再研究一下,'OnStart'方法太晚了,服務已經啓動了。下面我發佈了適合我的解決方案。 – Backs