我做了一个在aspnet核心网站上开发时运行的后台服务
public class VueService : BackgroundService
{
private readonly Microsoft.Extensions.Hosting.IHostingEnvironment hostingEnvironment;
private readonly ILogger<VueService> logger;
public VueService(Microsoft.Extensions.Hosting.IHostingEnvironment hostingEnvironment, ILogger<VueService> logger)
{
this.hostingEnvironment = hostingEnvironment;
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
System.Diagnostics.Process process = new System.Diagnostics.Process()
{
EnableRaisingEvents = true
};
try
{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
// startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C npm run serve";
startInfo.WorkingDirectory = hostingEnvironment.ContentRootPath;
process.StartInfo = startInfo;
// redirect the output
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
// hookup the eventhandlers to capture the data that is received
process.OutputDataReceived += (sender, args) => logger.LogInformation(args.Data);
process.ErrorDataReceived += (sender, args) => logger.LogError(args.Data);
// direct start
process.StartInfo.UseShellExecute = false;
process.Start();
// start our event pumps
process.BeginOutputReadLine();
process.BeginErrorReadLine();
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000);
}
}catch(Exception ex)
{
}
finally
{
try
{
process.Kill();
}
catch (Exception)
{
}
}
}
}
当应用程序停止/调试结束时,我如何确保它不会徘徊?
答案 0 :(得分:1)
如果后台服务是nodejs服务,请在启动类中尝试
SELECT REGEXP_REPLACE('6/11/10 21:19', '.* ([0-9]+):.*', '$1') AS hour
FROM yourTable;
即使在被杀死的Web应用程序上,它也可以正常终止nodejs服务。
答案 1 :(得分:0)
ASP.NET Core hosted services(包括BackgroundService
实例)在进程内运行。当进程退出时,它们将终止。