2

I have created a background service in C#. Last week I moved it to my virtual machine, I created a service as sc.exe create NameOfService binPath= blabla and worked perfectly until Sunday (yesterday 2/13/2023 11:58 PM). Today when I checked the event viewer I saw below error. If I run it as executable (.exe) it works smoothly, no problem. But when I start the service, it triggers that error. Does anyone know why?

Application: SE.Worker.SystemStatus.exe
CoreCLR Version: 4.700.20.11803
.NET Core Version: 3.1.3
Description: The process was terminated due to an unhandled exception.
Exception Info: System.OperationCanceledException: The operation was canceled.
   at System.Threading.CancellationToken.ThrowOperationCanceledException()
   at Microsoft.Extensions.Hosting.Internal.Host.StopAsync(CancellationToken cancellationToken)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.WaitForShutdownAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost host, CancellationToken token)
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at SE.Worker.SystemStatus.Program.Main(String[] args) in D:\App\Solution\SE.Worker.SystemStatus\Program.cs:line 12

Code program.cs

 public static void Main(string[] args) => CreateHostBuilder(args).Build().Run();

        public static IHostBuilder CreateHostBuilder(string[] args) =>
           Host.CreateDefaultBuilder(args).UseWindowsService()
               .ConfigureLogging(logging =>
               {
                   logging.ClearProviders();
                   logging.AddConsole();
                   logging.AddEventLog();
               })
               // Essential to run this as a window service
               .ConfigureServices(configureServices);

        private static void configureServices(HostBuilderContext context, IServiceCollection services)
        {
            services.Configure<StatusConfig>(context.Configuration.GetSection("Status"));
            services.AddLogging();

            services.AddSingleton<IVersionProcess, SystemStatusProcess>();
            services.AddHostedService<SystemStatusWorker>();
}
}}

ISystemStatus.cs

public class SystemStatusWorker : BackgroundService
    {
        private readonly ISystemStatusProcess systemStatusProcess;
        private readonly ILogger<SystemStatusWorker> logger;

        public SystemStatusWorker(ISystemStatusProcess systemStatusProcess, ILogger<SystemStatusWorker> logger)
        {
            this.systemStatusProcess = systemStatusProcess;
            this.logger = logger;
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                logger.LogInformation("SystemStatus Worker running at: {time}", DateTimeOffset.Now);
                await systemStatusProcess.GetSystemStatus();
            }
        }
    }
Paul Viorel
  • 234
  • 1
  • 11
  • Care to share the source code? Seems like you have a bug in it. – Eric Herlitz Feb 13 '23 at 08:19
  • This could be happening when you have an unhandled exception in your code. One possible solution could be to wrap the code of the background service with a try-catch block to handle the exception and log the error message. This can help you identify the root cause and fix the code to prevent the termination of the service. – Vadim Martynov Feb 13 '23 at 08:22
  • I added the code, the problem is that it works perfectly when I run it as executable (.exe). There is no triggered exception. – Paul Viorel Feb 13 '23 at 08:25
  • That error shows that the service was stopped, not that it changed behavior. As you write in the question, the application *does* work as a service. – Panagiotis Kanavos Feb 13 '23 at 08:29
  • Did you know that tutorial? https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service#install-nuget-package – Sir Rufo Feb 13 '23 at 08:31
  • @PanagiotisKanavos Hmm, so that means that there is no bug in the code. Just something is stopping the service? – Paul Viorel Feb 13 '23 at 08:31
  • BTW .NET Core 3.1 reached End-of-Life last year. The current Long-Term-Support version is .NET 6, supported until 2024. – Panagiotis Kanavos Feb 13 '23 at 08:31
  • 1
    The service runs under a different path, perhaps its trying to find a file (appsettings.json?) and it can't find it? It could also have to do with with rights of the service, windows services runs under a differnet account. Maybe give the folder your app runs in read/execute rights to everyone. These are 2 common issues when something works as .exe vs as windows service - however in both cases usually there is an appropriate exception so this seems not likely. It seems like some error happens and the service then shuts down, maybe add file logging? – sommmen Feb 13 '23 at 08:35
  • @PaulViorel there's both a bug (of shorts) and something is stopping the service. You're using `Run`, which does run as a normal executable, not as a service. [Create a Windows Service using BackgroundService](https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service?source=recommendations) shows how to create a Windows Service. The real difference is adding `UseWindowsService` to start listening for service commands and set up the Event log name. Had you used that you'd see log messages for stop/shutdown commands. – Panagiotis Kanavos Feb 13 '23 at 08:41
  • Perhaps there was a reboot of the machine? In that case your application would shut down abruptly. A normal service would receive the `Stop` command and trigger the cancellation token – Panagiotis Kanavos Feb 13 '23 at 08:43
  • @PanagiotisKanavos there was no reboot. Checked the uptime, it is 27 days uptime.. – Paul Viorel Feb 13 '23 at 13:06
  • Solved the problem. I upgraded the application to `.net6` and all packages to latest versions, then I moved all the release files to vps. There it worked as executable, but when I created the service, and this time it triggered an sql error (something about converting varchar datetime). Easy to solve that, but I am still curious why it worked until Sunday evening. – Paul Viorel Feb 14 '23 at 10:12

0 Answers0