【发布时间】:2011-12-24 00:13:40
【问题描述】:
我有一个 Windows 窗体,它使用
创建同一程序的多个控制台应用程序(它调用 program.exe 任意次数)process.start().
我正在寻找一种方法来识别应用程序的特定运行并彻底终止它(即彻底关闭 program.exe 的第 5 个进程,但让所有其他进程保持运行)。我能够通过进程启动时提供的 ID 来识别 program.exe 的每个不同进程,但除了调用之外,我无法以任何方式关闭应用程序
process.kill()
它不执行应用程序的干净关闭。
我相信我不能使用
process.CloseMainWindow()
因为应用程序没有窗口(它通过在后台运行的控制台运行)。在我从正在运行的进程列表中选择要终止的进程后,我希望通过单击 GUI 中的按钮终止这些进程。
我需要这个的原因是因为我需要在每个进程关闭之前关闭所有线程和未完成的方面。
我对每个新进程的定义如下,
Process process = new Process();
process.StartInfo = info;
ExecutionDetails details = new ExecutionDetails(run_id, process, info, session_type, strategy_type, name, ExecutionViewModel);
lock (_runs)
_runs.Add(run_id, details); // will throw on Add if duplicate id, prevent duplicate
ExecutionViewModel.NewRun(details); // add to the view model
process.Start();
其中 run_id 是标识每个进程的 GUID。
在一个单独的类中,我有通过进程执行的代码,该进程仅通过启动程序的命令提示符引用(即调用程序、提供配置变量等)。
有什么方法可以干净地关闭进程吗?我在想,当我想终止进程时调用一个事件可能会起作用,但到目前为止,我无法让这个想法起作用,因为我无法指定我想要关闭哪个进程。
** 编辑 - 我试图隐含的事件处理代码,但它不起作用。
主窗口中的代码
public void KillOne() {
foreach (var details in _runs.Values) {
if(details.IsSelected) {
StrategyStateManager.SessionClosed(this, details.RunId);
} } }
StrategyStateManager 中的代码(用于保存要在程序中使用的变量和事件的中间类)
public delegate void StrategyCloseEventHandler(object sender, StrategyCloseEventArgs e);
public static void SessionClosed(object sender, Guid id)
{
if(CloseSession != null)
CloseSession(sender, new StrategyCloseEventArgs(id));
}
public class StrategyCloseEventArgs : EventArgs
{
private readonly Guid id;
public StrategyCloseEventArgs(Guid run_id)
{
id = run_id;
}
public Guid GetRunID()
{
return id;
}
}
正在由主窗口启动的进程中的代码
StrategyStateManager.CloseSession += (closeStrategy);
void closeStrategy(object sender, StrategyCloseEventArgs e)
{
if (e.GetRunID() == run_id)
{
strategy.cleanupForShutdown();
DBSaverSimple.shutdownAll();
logger.Warn("Simulation run stopped by user");
}
}
【问题讨论】: