简体   繁体   English

如果我没有在C#控制台应用程序中关闭System.Diagnostics.Process,该怎么办?

[英]What happens if I don't close a System.Diagnostics.Process in my C# console app?

I have a C# app which uses a System.Diagnostics.Process to run another exe. 我有一个使用System.Diagnostics.Process来运行另一个exe的C#应用​​程序。 I ran into some example code where the process is started in a try block and closed in a finally block. 我遇到了一些示例代码,其中该过程在try块中启动,在finally块中关闭。 I also saw example code where the process is not closed. 我还看到了未关闭该过程的示例代码。

What happens when the process is not closed? 如果不关闭流程会怎样?

Are the resources used by the process reclaimed when the console app that created the process is closed? 关闭创建进程的控制台应用程序时,是否回收了该进程使用的资源?

Is it bad to open lots of processes and not close any of them in a console app that's open for long periods of time? 打开许多进程而不在长时间打开的控制台应用程序中关闭其中任何一个进程是否很糟糕?

Cheers! 干杯!

When the other process exits , all of its resources are freed up, but you will still be holding onto a process handle (which is a pointer to a block of information about the process) unless you call Close() on your Process reference. 当其它进程退出时所有资源都被释放了,但你仍然会持有到一个进程句柄(这是一个指针的信息有关的处理的模块),除非你调用Close()在你的Process的参考。 I doubt there would be much of an issue, but you may as well . 我怀疑会有很多问题,但您也可能会 Process implements IDisposable so you can use C#'s using(...) statement, which will automatically call Dispose (and therefore Close() ) for you : Process实现了IDisposable因此您可以使用C#的using(...)语句,该语句将自动为您调用Dispose (并因此调用Close() ):

using (Process p = Process.Start(...))
{
  ...
}

As a rule of thumb: if something implements IDisposable , You really should call Dispose / Close or use using(...) on it. 作为一个经验法则:如果某个东西实现了IDisposable ,那么您实际上应该调用Dispose / Close或在其上使用using(...)

它们将继续运行,就像您自己启动它们一样。

A process is a standalone entity. 流程是一个独立的实体。 Programatically creating a process is much the same as launching a process from your desktop. 以编程方式创建进程与从桌面启动进程几乎相同。

The handle to a process you create is only returned for convenience. 您创建的流程的句柄只是为了方便而返回。 For example to access its input and output streams or (as you saw) to kill it. 例如,访问其输入和输出流或(如您所见)将其杀死。

The resources are not reclaimed when the parent process is killed. 终止父进程时,不会回收资源。

The only time it is bad to open lots of processes is if you open so many that the CPU and RAM cannot handle it! 打开很多进程的唯一不好的情况是打开的进程太多,以致CPU和RAM无法处理!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM