在构建中停止并启动Windows服务

时间:2019-07-02 16:30:18

标签: c# visual-studio windows-services

我们要在重新构建Windows Service之前先停止其Windows Service,然后构建新版本,然后将其复制到指定的文件夹(由于配置更改,将exe置于不同的bin文件夹中)。然后重新启动Windows服务。听起来很简单,但是我们遇到的主要问题是停止服务不会立即释放文件锁。导致构建失败。 (一次停止该服务,一次真正复制并重新启动它)

目前,如上所述,我们确实有50%的时间可以正常工作的方式。但是,每次我们更改解决方案时都必须构建两次,这很烦人。当前的方法是在项目级别上构建事件。

Prebuild看起来像这样:

cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
net start | find "ServiceHost"
if Not ERRORLEVEL 1 InstallUtil.exe -u 
$(ProjectDir)bin\Current\ServiceHost.exe
Exit /b 0

和PostBuild看起来像这样:

cd $(ProjectDir)bin
DEL Current\* /F /Q /S
xcopy $(Configuration) Current
cd C:\Windows\Microsoft.NET\Framework\v4.0.30319
InstallUtil.exe $(ProjectDir)bin\Current\ServiceHost.exe
net start ServiceHost
Exit /b 0

还有一个初始创建“当前”文件夹的问题,因为我们的源代码控制没有保留Bin文件夹。我们可以在其中添加mkdir current命令来解决此问题。如果有更好的方法来更新服务,则您的建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

我有一个可行的解决方案。它不理想,但似乎确实可以100%地起作用

预构建:

net stop ServiceHost
:delete
cd $(ProjectDir)
rmdir /s /q $(ProjectDir)bin\Current
echo delete Error Level %ERRORLEVEL%
goto checkDelete
:checkDelete
cd $(ProjectDir)bin\Current
echo check Error Level %ERRORLEVEL%
if %ERRORLEVEL% == 1 (GOTO end) else (GOTO retry)
:retry
echo Prebuild Retry after 5 seconds
powershell -command "Start-Sleep -s 5"
GOTO delete
:end
echo Prebuild Terminate
Exit /b 0

发布后的版本:

cd $(ProjectDir)bin
:copy
mkdir Current
xcopy $(Configuration) Current
echo PostBuild  Error Level %ERRORLEVEL%
if not %ERRORLEVEL% == 0 (GOTO copy)
echo starting service
net start ServiceHost
Exit /b 0
相关问题