Background services deployed as Windows Services stopped working. It happened after we migrated from .Net core 3.1 to .Net 6. Services are created using IHosted Service. Services are type of Time Interval and Messaging Queue service and all stopped working. As soon as we start the service, after some initial processing Like connecting to Queuing server successfully or fetching data from DB, the service stops. No logging error is generated and windows event viewer shows service terminated unexpectedly. It has done this x time(s) without any details. When we run the service as console, it gives no error or exception but close after the same steps. In debug mode, the console application is working on all type of services as expected without exiting. Our initial thought by observing all services is, as soon as the service becomes idle, it exits.
We also have a Web App, which is deployed on same server and is working fine. Our server is Windows Server 2012 R2. We have installed Runtime as well as SDK for .Net6. This is our Program.cs file code
public static void Main(string[] args)
{
var isService = !(Debugger.IsAttached || args.Contains("--console"));
var builder = CreateHostBuilder(args, isService);
var task = isService ? builder.StartAsync() : builder.RunConsoleAsync();
task.Wait();
}
public static IHostBuilder CreateHostBuilder(string[] args, bool isService)
{
var hostBuilder = Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<MyHostedService>();
})
.ConfigureLogging(logging =>
{
logging.ClearProviders().AddConsole().AddNLog();
if (isService){
logging.AddEventLog(config =>
{
config.LogName = serviceName;
config.SourceName = serviceName;
});}
});
if (isService){
hostBuilder.UseWindowsService();
}
return hostBuilder;
}
And our service code is below
public class MyHostedService: IHostedService
{
public Task StartAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Timed Hosted Service running.");
Start();
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Timed Hosted Service is stopping.");
Stop();
return Task.CompletedTask;
}
}