Repository navigation
Open
Labels
Milestone
Description
Describe the bug
When using .UseWindowsService(), the windows service always reports success from startup, regardless of whether the host actually starts up successfully.
A clear and concise description of what the bug is.
To Reproduce
- Use the code below.
- Start the service with net start.
Expected behavior
Net start indicates the service failed to start.
Actual behavior
Net start indicates the service started successfully.
Additional context
Note that on some older versions of .NET Framework (pre 4.7.2 maybe), service startup exceptions aren't propagated correctly.
Program.cs:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
static class Program
{
static void Main()
{
new HostBuilder()
.ConfigureLogging(l => l.AddConsole())
.ConfigureServices((s) =>
{
s.AddHostedService<TestService>();
})
.UseWindowsService()
.Build()
.Run();
}
}
class TestService : IHostedService
{
readonly ILogger log;
public TestService(ILogger<TestService> log)
{
this.log = log;
}
public Task StartAsync(CancellationToken cancellationToken)
{
log.LogInformation("Starting...");
throw new InvalidOperationException("Test when startup always fails.");
//log.LogInformation("Started.");
//return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
log.LogInformation("Stopping...");
log.LogInformation("Stopped.");
return Task.CompletedTask;
}
}TestHostBuilder.csproj:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9463B6C5-BC95-43AA-968F-651084C85DAE}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>TestHostBuilder</RootNamespace>
<AssemblyName>TestHostBuilder</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting">
<Version>3.1.0</Version>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices">
<Version>3.1.0</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>```Reacted by Kyle McClellan, Filip Vukovinski, its-mash and Kalle Olavi Niemitalo
Activity
davidmatson commentedon Jan 6, 2020
The problematic line of code appears to be:
https://github.com/aspnet/Extensions/blob/b83b27d76439497459fe9cf7337d5128c900eb5a/src/Hosting/WindowsServices/src/WindowsServiceLifetime.cs#L91
The actual service startup logic only unblocks the app from starting - it doesn't wait for the app to start and throw an exception if startup fails.
If the OnStart method awaited a task that does actual host/app startup, that would likely fix the problem. (It would also fix the problem that the Windows Service is reporting as started before it is fully started, which is another related bug that currently exists.)
davidmatson commentedon Jan 8, 2020
I think .UseWindowsService() may just not be possible to do correctly - the Service class and IHostLifetime abstractions just don't match. Particularly, the Service class expects all startup logic to live inside OnStart, and for the program not to do anything that might throw before then.
I tried ways to solve this bug as well as #50018. The only solution I found to both was not to use UseWindowsService at all. An IHostLifetime isn't told about exception starting up hosted services. The best it can do is know if the application has started via IHostApplicationLifetime, but it won't know when an exception in Internal\Host.cs's startup means that method will never get called. I even tried using AppDomain.CurrentDomain.UnhandledException, but that doesn't work all the time (only works if the program doesn't handle exceptions), and doesn't allow the service to report startup failure, only to have it terminate abnormally.
Here's what I ended up doing - use only WindowsServiceHelpers.IsWindowsService() and not .UseWindowsService(). Having all startup for a Windows services happen inside Service.OnStart is how that API is intended to work, and all these bugs go away when it's used that way.
kmcclellan commentedon Aug 22, 2020
Here's a workaround that still leverages the functionality of
UseWindowsService()andWindowsServiceLifetime. Hoping this gets fixed at some point and I can remove this from my application!davidmatson commentedon Sep 25, 2025
/keep-alive
kjkrum commentedon Sep 25, 2025
Delete that bot. Inactivity is NEVER a valid reason to close a detailed bug report.