简体   繁体   中英

IHostedService mirgrated from .Net Core 3.1 to .Net 6 stops working

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

Just found the solution. After creating the hostbuilder and attaching all services by using this code,

var hostBuilder = Host.CreateDefaultBuilder(args);

we were calling StartAsync to start the service

var task = builder.StartAsync();
task.Wait();

instead, host should be Build and then Run to start the service

 var task = builder.Build().RunAsync();
 task.Wait();

In .Net Core 3.1 we were using StartAsync which was working fine. After migrating to .Net6 , this stoppped working. By using the same code in .Net6 , background service when become idle, gets shutdown. Build().RunAsync() keeps the service alive, even after it become idle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM