Windows服务无法启动 '错误1053: 服务未能在适当的时间内响应启动或控制请求'

4

我目前正在开发一个Windows服务,作为我们应用程序的非GUI部分。我编写了一个服务,在调试条件下,完美地工作。这意味着我通过以下方式来进行调试:

static void Main()
{
    MyService service = new MyService();
    service.OnDebug();
    Thread.Sleep(Timeout.Infinite);
}

#if(!DEBUG)
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] 
    { 
        new TRAservice() 
    };
    ServiceBase.Run(ServicesToRun);
#else
    TRAservice Service = new TRAservice();
    Service.CanHandlePowerEvent = false;
    Service.CanHandleSessionChangeEvent = false;
    Service.CanPauseAndContinue = true;
    Service.CanShutdown = true;
    Service.CanStop = true;
    Service.ServiceName = "TRAservice";
    Service.AutoLog = false;
    Service.SetMethod();
    Service.TRAmethod();
#endif

为了进行一些实现测试,我添加了一个ProjectInstaller,并通过VStools命令提示符安装我的服务,使用installutil servicename.exe命令进行安装。 (供参考,我在此帖子底部包含了OnStart的服务构造函数。)
然而,当我尝试启动服务时,我会收到以下错误: error 在我的事件查看器中,我得到4条消息(2个信息(Windows错误报告),2个错误): Error Error 我已经尝试了很多方法,包括但不限于删除构造函数中的调试行(如其他地方建议的),重新启动,从Release(而不是Debug)安装...
我将接受任何解决此问题的建议。先感谢您。
public TRAservice()
{
    InitializeComponent();

    CanHandlePowerEvent = false;
    CanHandleSessionChangeEvent = false;
    CanPauseAndContinue = true;
    CanShutdown = true;
    CanStop = true;
    ServiceName = "TRAservice";
    AutoLog = false;

    sSource = "TRAservice";
    sLog = "TRAlog";

    if (!EventLog.SourceExists(sSource))
    {
        EventLog.CreateEventSource(sSource, sLog);
    }

    eventLog1 = new System.Diagnostics.EventLog();
    eventLog1.Source = sSource;
    eventLog1.Log = sLog;

    eventLog1.WriteEntry("Service started", EventLogEntryType.Information, 1, 100);

    scheduleTimer = new Timer();
    scheduleTimer.Interval = 10;
    scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);;
}

protected override void OnStart(string[] args)
{
    eventLog1.WriteEntry("Service started", EventLogEntryType.Information, 1, 100);
    flag = true;
    sw = true;
    lastRun = DateTime.Now;
    scheduleTimer.Start();
}

3
应该在安装程序类中创建事件源,而不是在服务类的构造函数中创建。服务将使用管理员权限安装,但它可能不总是在管理员权限下运行 - Damien_The_Unbeliever
谢谢。当我实施您的建议时,安装服务时出现以下错误: 在安装阶段发生异常。 System.ArgumentException: 在本地计算机上源TRAservice已经存在。 然而,即使我从注册表中删除它,这个错误仍然不断弹出。有什么建议吗? - Shishdem
2个回答

4
在我的Windows服务中,我添加了一个控制台应用程序项目,并将其设置为默认启动项目。我使用它来调试与Windows服务启动相同的代码库。我在一个单独的类库项目中拥有可工作的代码。
我的Windows服务项目只有一个service.cs文件、projectinstaller.cs和app.config文件,我已经复制到我的控制台应用程序中。我没有使用任何编译器指令来运行不同的代码集。
请参见此MSDN页面。这个页面和子页面对于安装和运行我的Windows服务非常有帮助。它引用了Visual Studio 2003,但对于我的Visual Studio 2013、.net 4.5.1 Windows服务应用程序也可以正常工作。
我做的一个配置是创建一个名为“Debug - Local”的新解决方案配置。我还创建了一个PowerShell脚本来卸载服务、构建解决方案并按照此配置安装服务。这样我就可以在我的日常工作中使用Debug配置,而不必担心文件被锁定。
脚本文件位于~/repoRoot/Tools,解决方案位于~/repoRoot/src。 以下是我的PowerShell脚本: p.s.我只在以管理员身份运行的PowerShell窗口中运行过此脚本,还没有尝试过“以管理员身份运行”部分...
#######################
# Run as Administrator
#######################
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{   
#"No Administrative rights, it will display a popup window asking user for Admin rights"

$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process "$psHome\powershell.exe" -Verb runAs -ArgumentList $arguments

break
}

cls

#############################################################
# Set environment variables for Visual Studio Command Prompt
#############################################################
function Set-VsCmd
{
    param(
        [parameter(Mandatory, HelpMessage="Enter VS version as 2010, 2012, or 2013")]
        [ValidateSet(2010,2012,2013)]
        [int]$version
    )
    $VS_VERSION = @{ 2010 = "10.0"; 2012 = "11.0"; 2013 = "12.0" }
    $targetDir = "c:\Program Files (x86)\Microsoft Visual Studio $($VS_VERSION[$version])\VC"
    if (!(Test-Path (Join-Path $targetDir "vcvarsall.bat"))) {
        "Error: Visual Studio $version not installed"
        return
    }
    pushd $targetDir
    cmd /c "vcvarsall.bat&set" |
    foreach {
      if ($_ -match "(.*?)=(.*)") {
        Set-Item -force -path "ENV:\$($matches[1])" -value "$($matches[2])"
      }
    }
    popd
    write-host "`nVisual Studio $version Command Prompt variables set." -ForegroundColor Yellow
}

Set-VsCmd 2013

#######################
# Stop windows service
#######################
$srvName = "Enterprise CQRS Service"
$serviceStop = Get-Service $srvName
"$srvName is now " + $serviceStop.status
Stop-Service $srvName

$TestService = Get-Service $srvName | Select-Object 'Status'
While($TestService | where {$_.Status -eq 'Running'}) {
    Write-Host '.'-NoNewLine 
  Sleep 2   
}
Write-Host "$srvName is now" $TestService.status -ForegroundColor Yellow

#################################
# Build Service as Debug - Local
#################################

# Set the solution file path
$scriptPath = Split-Path -parent $MyInvocation.MyCommand.Definition

$solutionFile = Join-Path $scriptPath "../src/Enterprise CQRS Service.sln"

# Build the Debug - Local configuration
msbuild $solutionFile /p:Configuration='Debug - Local'

##############################
# Uninstall & Instal Service
##############################

# Set the exe file path
$exePath = Join-Path $scriptPath "../src/Enterprise.Services.Windows/bin/Debug - Local/Enterprise.Services.Windows.exe"

# Uninstall the service
installutil /u $exePath

# Install the service
installutil $exePath

# Start the service
$servicePrior = Get-Service $srvName
"$srvName is now " + $servicePrior.status
Start-Service $srvName
$serviceAfter = Get-Service $srvName
$foregroundColor = "Green"
if($serviceAfter.status -ne "Running")
{
    $foregroundColor = "Red"
}
Write-Host "$srvName is now" $serviceAfter.status -ForegroundColor $foregroundColor

希望这能帮到您!

非常感谢你的输入!由于我终于可以结束今天的工作了,明天我会研究这个问题。 - Shishdem

0

几天前我遇到了这个问题,我试图将一个 .Net 4.5 服务安装到 Windows 2012 服务器上。 不管怎样, 我将 .Net 3.5 框架安装到了 Windows Service 2012 上,它运行得很好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接