c# - 将控制台应用程序作为后台进程运行@ .NET 5
问题描述
我们已经从 .NET Framework 迁移到 .NET 5,以将我们的应用程序部署到 linux 和 windows。
最初我们使用的是 Windows 应用程序,为了支持跨平台部署,我们已迁移到控制台应用程序。
是否可以选择将其作为后台进程运行?
这建议转换为 Windows 应用程序,但这不是一个选项。
谢谢。
解决方案
在程序 .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);
}
}
推荐阅读
- go - 在 golang 程序中运行交互式 shell 脚本
- reactjs - 带钩子的 useEffect 给了我一个警告信息
- html - 如何将我的文本调整为我的屏幕尺寸,并固定位置
- ios - 将 UITableViewController 转换为 SwiftUI 后,UITableViewCell 中的视图为零
- php - 如何从php中的字符串数组中获取数组?
- python - 如何从使用 Python 返回文本的 API 将文本解析为 json
- python - 如何在 APScheduler 中即时修改作业?
- c++ - 如何在 C++ 中进行线程安全的光线投射?
- sockets - MP Chart 在颤动中使用套接字
- python-3.x - 将 jsondata 保存到自己的 .json 文件中