在 C# .NET 中启动和停止进程
我正在尝试编写一个简单的程序,它有两种方法,一种启动进程,一种停止同一进程。 如:
public Process StartProc(string procname)
{
Process proc = new Process();
proc.StartInfo.FileName = procname;
proc.Start();
return proc;
}
public void StopProc(Process proc)
{
proc.Close();
}
可以这样做吗?
I am trying towrite a simple program that has two methods, one that starts a process and one that takes down the same process.
as in:
public Process StartProc(string procname)
{
Process proc = new Process();
proc.StartInfo.FileName = procname;
proc.Start();
return proc;
}
public void StopProc(Process proc)
{
proc.Close();
}
Is it possible to do this like that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,您使用的方法称为
Kill
,而不是Close
:这将强制关闭进程 - 如果可能,最好向应用程序发出关闭信号,例如请求应用程序关闭主窗口:
这允许应用程序执行清理逻辑(例如保存文件),但是如果它选择忽略请求,则可能允许进程继续运行,并且如果进程没有主窗口(例如使用控制台应用程序),则不会执行任何操作。
有关详细信息,请参阅有关
进程的文档。 CloseMainWindow
方法。Yes, the method you are after is called
Kill
, notClose
:This will forcibly close the process - when possible it is preferable to signal the application to close such as by requesting that the application close the main window:
This allows the application to perform clean-up logic (such as saving files), however may allow the process to continue running if it chooses to ignore the request and will do nothing if the process does not have a main window (for example with a console application).
For more information see the documentation on the
Process.CloseMainWindow
method.我认为您正在寻找
Process.Kill( )
。您实际上并不需要
StopProc()
方法,您可以直接编写proc.Kill()
。但是,通常不建议您以如此残酷的方式终止进程。这样做可能会使共享对象处于未定义状态。如果您能找到一种方法来合作关闭该流程,那就是首选。
I think you are looking for
Process.Kill()
.You don't really need a
StopProc()
method, you can just writeproc.Kill()
directly.However, it is not generally recommended that you terminate processes in such a brutal way. Doing so can leave shared objects in an undefined state. If you can find a way to co-operatively close the process that is to be preferred.
通过启动进程,您可以获得该进程的唯一 ID,然后您可以像这样杀死它:
By starting the process, you can get the unique Id of that process and then you can kill it like this: