在做Process.Start()时你需要将它包装在一个使用中吗?

时间:2023-01-26 20:45:45

When you are starting a process and dont care about the result is this ok?

当你开始一个过程并且不关心结果时这可以吗?

Process.Start(xxx);

Or should you do this

或者你应该这样做

using (Process.Start(xxx)){}

2 个解决方案

#1


6  

Looking at the implementation of the Process.dispose(bool) method shows that it calls Close() on the Process instance. This in turn cleans up the native process handle so its probably not a bad idea.

查看Process.dispose(bool)方法的实现显示它在Process实例上调用Close()。这反过来会清理本机进程句柄,所以它可能不是一个坏主意。

It also cleans up a wait handle that it uses to check if the process has exited.

它还会清理一个等待句柄,用于检查进程是否已退出。

Even if you don't use the using (...) block the finalizer will catch these resources in the end.

即使您不使用using(...)块,终结器也会最终捕获这些资源。

#2


3  

The Process object that is returned by Process.Start contains a Windows process HANDLE, so it should be disposed once you no longer need to use the Process object.

Process.Start返回的Process对象包含一个Windows进程HANDLE,因此一旦不再需要使用Process对象就应该处理它。

If you don't need to use the returned Process object at all, then the empty using block that you show is fine. Note that disposing the Process releases the handle but it (fortunately) does not stop the process from executing.

如果您根本不需要使用返回的Process对象,那么您显示的空使用块就可以了。请注意,处理Process会释放句柄,但幸运的是它不会阻止进程执行。

#1


6  

Looking at the implementation of the Process.dispose(bool) method shows that it calls Close() on the Process instance. This in turn cleans up the native process handle so its probably not a bad idea.

查看Process.dispose(bool)方法的实现显示它在Process实例上调用Close()。这反过来会清理本机进程句柄,所以它可能不是一个坏主意。

It also cleans up a wait handle that it uses to check if the process has exited.

它还会清理一个等待句柄,用于检查进程是否已退出。

Even if you don't use the using (...) block the finalizer will catch these resources in the end.

即使您不使用using(...)块,终结器也会最终捕获这些资源。

#2


3  

The Process object that is returned by Process.Start contains a Windows process HANDLE, so it should be disposed once you no longer need to use the Process object.

Process.Start返回的Process对象包含一个Windows进程HANDLE,因此一旦不再需要使用Process对象就应该处理它。

If you don't need to use the returned Process object at all, then the empty using block that you show is fine. Note that disposing the Process releases the handle but it (fortunately) does not stop the process from executing.

如果您根本不需要使用返回的Process对象,那么您显示的空使用块就可以了。请注意,处理Process会释放句柄,但幸运的是它不会阻止进程执行。