You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
With UseWindowsService, when main thread exits, service is left running and can't be stopped #2836
If a host uses UseWindowsService and its If Program.Main returns without throwing (for example, catches and logs unhandled top-level exceptions), the Windows service is left in the running status and can't be stopped - only killing the processing works.
To Reproduce
Use the code below.
Start the service.
Try to stop the service.
Expected behavior
The service is either not started or stops successfully.
Actual behavior
The service is stuck running and cannot be stopped.
Additional context
Program.cs:
usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.Extensions.Hosting;usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;classProgram{publicstaticvoidMain(){try{newHostBuilder().ConfigureServices(s =>{s.AddHostedService<TestService>();}).UseWindowsService().Build().Run();}catch{// Log or something similar; anything other than rethrowing/throwing...}}classTestService:IHostedService{publicTaskStartAsync(CancellationTokencancellationToken){thrownewNotImplementedException();}publicTaskStopAsync(CancellationTokencancellationToken){returnTask.CompletedTask;}}}
As a more real-world example, here's a Program.Main I'm using in practice that triggers this behavior:
publicstaticintMain(){try{Run();// HostBuilder Run etc here...return0;}catch(Exceptionexception){Console.Error.WriteLine(exception);returnexception.HResult;}}
(Which happens to return a failed exit code from the process without having an unhandled exception set to the .NET runtime.)
newThread(Run).Start();// Otherwise this would block and prevent IHost.StartAsync from finishing.
and don't make it a background thread. That's probably why it's not shutting down properly. Should be an easy fix: Just make the thread a background thread.
Activity
davidmatson commentedon Jan 8, 2020
As a more real-world example, here's a Program.Main I'm using in practice that triggers this behavior:
(Which happens to return a failed exit code from the process without having an unhandled exception set to the .NET runtime.)
analogrelay commentedon Apr 24, 2020
Triage: We create a new thread in
extensions/src/Hosting/WindowsServices/src/WindowsServiceLifetime.cs
Line 64 in 88ba1c8