我用下面的代碼安裝Windows服務:註冊Windows服務
ServiceBase.Run(new ServiceProcess(serviceName, serviceArgs));
從documentation我明白了,這個方法也呼籲服務OnStart
方法。但我想將服務安裝爲已停止並稍後手動啓動它。
我用下面的代碼安裝Windows服務:註冊Windows服務
ServiceBase.Run(new ServiceProcess(serviceName, serviceArgs));
從documentation我明白了,這個方法也呼籲服務OnStart
方法。但我想將服務安裝爲已停止並稍後手動啓動它。
我研究了我們的項目,發現自定義安裝。我忽略了方法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;
}
}
private static InitialStartDone = false; // declared in service class
protected Overrride void OnStart(string[] args);
{
if(!InitialStartDone)
{
InitialStartDone = true;
}
else
{
base.OnStart(args);
}
}
嘗試覆蓋上開始的默認行爲,使用靜態變量來檢測,如果它被稱爲第一次
如果安裝後停止服務,該怎麼辦?這對你有用嗎? – Viru
@Viru這是一個選項,但我擔心服務可以在停止之前執行一些操作,這對我的應用程序不利。所以我試圖找到解決方案來避免這個 – Backs
雅得到它,但在這種情況下,你必須重寫onStart方法,並提供你自己的實現,你可以檢查它是否是第一次啓動,如果是的話,那麼不要調用開始 – Viru