如果我不关闭 C# 控制台应用程序中的 System.Diagnostics.Process 会发生什么? [英] What happens if I don't close a System.Diagnostics.Process in my C# console app?

查看:12
本文介绍了如果我不关闭 C# 控制台应用程序中的 System.Diagnostics.Process 会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C# 应用程序,它使用 System.Diagnostics.Process 来运行另一个 exe.我遇到了一些示例代码,其中进程在 try 块中启动并在 finally 块中关闭.我还看到了流程未关闭的示例代码.

I have a C# app which uses a System.Diagnostics.Process to run another exe. I ran into some example code where the process is started in a try block and closed in a finally block. 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?

干杯!

推荐答案

当另一个进程退出时,的所有资源都被释放了,但你仍然会除非您在 Process 引用上调用 Close() ,否则保持进程句柄(它是指向有关进程的信息块的指针).我怀疑会有很多问题,但是你也可以.Process 实现了 IDisposable 所以你可以使用 C# 的 using(...) 语句,它将自动为您调用 Dispose(因此为 Close()):

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. 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 :

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

根据经验:如果某些东西实现了 IDisposable,你真的应该调用 Dispose/Close 或在其上使用 using(...).

As a rule of thumb: if something implements IDisposable, You really should call Dispose/Close or use using(...) on it.

这篇关于如果我不关闭 C# 控制台应用程序中的 System.Diagnostics.Process 会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆