我做了一个后台服务,在aspnet核心web上开发时运行。
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)
{
}
}
}
}当应用程序停止/调试结束时,我如何确保它不会挂起?
发布于 2019-05-16 12:03:24
如果您的后台服务是nodejs服务,请在您的启动类中尝试这样做
//ConfigureServices
services.AddNodeServices(node => node.ProjectPath = Path.GetFullPath("path/to/nodejs/project"));
//Configure
app.UseSpa(spa =>
{
app.ApplicationServices.GetRequiredService<INodeServices>().InvokeAsync<object>("path/to/your/entry.js");
spa.UseProxyToSpaDevelopmentServer("http://localhost:3000"); //remove it if you don't need asp.net core application to proxy for your background service
});它可以正确地终止nodejs服务,即使在被终止的web应用程序上也是如此。
发布于 2019-05-15 20:53:28
ASP.NET Core hosted services (包括BackgroundService实例)在进程内运行。当进程退出时,它们将被终止。
https://stackoverflow.com/questions/56148654
复制相似问题