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();
}
}
}