首页 > 解决方案 > 将控制台应用程序作为后台进程运行@ .NET 5

问题描述

我们已经从 .NET Framework 迁移到 .NET 5,以将我们的应用程序部署到 linux 和 windows。

最初我们使用的是 Windows 应用程序,为了支持跨平台部署,我们已迁移到控制台应用程序。

是否可以选择将其作为后台进程运行?

建议转换为 Windows 应用程序,但这不是一个选项。

谢谢。

标签: c#.net-coreconsole-application.net-5

解决方案


在程序 .cs

  public static class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                });

    }

并创建 Worker.cs 文件,您需要在其中编写这些代码行以启动调度程序服务

    public class Worker : BackgroundService
    {
        private readonly string l_ClassName = "Worker";
        public Worker()
        {
        }
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            string l_FuncName = "OnStart";
            using (new FuncTracer(l_ClassName, l_FuncName))
            {
                try
                {
                    Logger.LogInformation(l_ClassName, l_FuncName, "Starting the Service");

                    var ScheduleServices = new ScheduleService().GetScheduleServices();

                    foreach (ScheduleJobServicesDto item in ScheduleServices)
                    {
                        if (item.ServiceEnabled)
                            switch (item.JobServiceId)
                            {
                              case 1:
                                  DataAvailabilityAndReconciliationService l_DataAvailabilityAndReconciliationService = new DataAvailabilityAndReconciliationService();
                                  l_DataAvailabilityAndReconciliationService.DoWork(123);
                                  break;
                            }
                    }
                    await Task.Delay(1000, stoppingToken);
                }
                catch (Exception ex)
                {
                    Logger.LogError(l_ClassName, l_FuncName, ex.Message);
                }

            }
        }


        public override Task StopAsync(CancellationToken cancellationToken)
        {
            string l_FuncName = "OnStart";
            Logger.LogInformation(l_ClassName, l_FuncName, "Stopping the Service");
            base.StopAsync(cancellationToken);
            Logger.LogInformation(l_ClassName, l_FuncName, "The Service Is Stopped");
            return Task.Delay(0, cancellationToken);
        }
    }

推荐阅读