问题描述
我有一个dotnet core 2.2控制台应用程序.
我将其托管为Windows服务.(服务名称:"MyService1")
"MyService1"启动另一个dotnet核心WebAPI.
问题是,当"MyService1"停止时,如何安全地终止WebAPI进程?
I have a dotnet core 2.2 console app.
I hosted it as windows service.(Service name: "MyService1")
"MyService1" starts up another dotnet core WebAPI.
The problem is, how do I safely kill the WebAPI process when the "MyService1" is stopped?
这是我尝试执行的操作,但是我仍然可以在任务管理器中看到该过程.
Here is how I tried to do that but I can still see the process in the task manager.
public class MyService : IHostedService, IDisposable
{
private Timer _timer;
static Process webAPI;
public Task StartAsync(CancellationToken cancellationToken)
{
_timer = new Timer(
(e) => StartChildProcess(),
null,
TimeSpan.Zero,
TimeSpan.FromMinutes(1));
return Task.CompletedTask;
}
public void StartChildProcess()
{
try
{
webAPI = new Process();
webAPI.StartInfo.UseShellExecute = false;
webAPI.StartInfo.FileName = @"C:\Project\bin\Debug\netcoreapp2.2\publish\WebAPI.exe";
webAPI.Start();
}
catch (Exception e)
{
// Handle exception
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
// TODO: Add code to stop child process safely
webAPI.Close();
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
是否可以在不使用Kill()方法的情况下做到这一点?
Is it possible to do that without using Kill() method?
推荐答案
我不确定您是从哪里开始其他WebAPI进程的,但您有2个选择:
I'm not sure where you're starting your other WebAPI process from, nut you have 2 options:
-
从您的
Program.cs
文件注册到ProcessExit
事件并关闭WebAPI在那里处理,就像这样:
Register to the
ProcessExit
event from yourProgram.cs
file and close the WebAPIprocess there, like this:
class Program
{
static Process webAPI;
static async Task Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
webAPI = new Process
{
StartInfo = new ProcessStartInfo("dotnet")
{
UseShellExecute = false,
CreateNoWindow = true,
//If you want to run as .exe
FileName = @"C:\Project\bin\Debug\netcoreapp2.2\publish\WebAPI.exe",
//If you want to run the .dll
WorkingDirectory = "C:/Project/publish",
Arguments = "WebAPI.dll"
}
};
using (webAPI)
{
webAPI.Start();
webAPI.WaitForExit();
}
}
static void CurrentDomain_ProcessExit(object sender, EventArgs e)
{
webAPI.Close();
}
}
将服务进程ID传递到WebAPI进程并从那里对其进行监视,如下所示:
Pass the service process id to the WebAPI process and monitor it from there, like this:
class Program
{
static async Task Main(string[] args)
{
try { }
catch { }
// Make sure you use a finally block.
// If for any reason your code crashes you'd still want this part to run.
finally
{
if (int.TryPasre(args[X], out parentProcessId))
MonitorAgentProcess(parentProcessId);
}
}
static void MonitorAgentProcess(int parentProcessId)
{
try
{
Process process = Process.GetProcessById(parentProcessId);
Task.Run(() => process.WaitForExit())
.ContinueWith(t => Environment.Exit(-1));
}
catch {}
}
}
这篇关于.net核心控制台应用程序作为Windows服务-是否可以在不使用Kill()方法的情况下安全地终止已启动进程的执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!