[英]Do I need to worry about Process in foreach loop
Here is the piece of code, which run through all the process and when It finds the right process, code sends the message. 以下是贯穿所有进程的代码段,当它找到正确的进程时,代码会发送消息。 My question is what happened to the 'proc', how to dispose that process. 我的问题是'proc'发生了什么,如何处理这个过程。
//get all other (possible) running instances
Process[] processes = Process.GetProcesses();
foreach (Process proc in processes)
{
if (proc.ProcessName.ToLower() == ProcessName.ToLower())
{
SendMessage(proc.MainWindowHandle, (uint)Message, IntPtr.Zero, IntPtr.Zero);
}
}
Thanks in advance, Harsha 哈尔莎,提前谢谢
To make sure all resoucers are freed as early as possible, call Dispose on the process, when you no longer need it. 为了确保尽快释放所有资源,请在不再需要时调用Dispose。
//get all other (possible) running instances
Process[] processes = Process.GetProcesses();
try
{
foreach (Process proc in processes)
{
// use proc
}
}
finally
{
foreach (Process proc in processes)
proc.Dispose();
processes = null;
}
In general terms you don't need to worry about disposing or deallocating objects, unless the object implements the IDisposable
interface. 一般而言, 除非对象实现IDisposable
接口, 否则您不必担心处置或取消分配对象。 If it does you should either call the Dispose()
method on it manually when you're finished, or wrap with a using
statement to have it called automatically: 如果是这样,您应该在完成时手动调用Dispose()
方法,或者using
语句自动调用它:
using (var disposableObject = new DisposableType())
{
// do work with disposableObject
}
IF you are looping to find your won process then you could try something like: 如果你循环找到你赢得的过程,那么你可以尝试类似的东西:
Process.GetCurrentProcess();
In any case I would change it to: 在任何情况下,我会将其更改为:
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.ToLower() == ProcessName.ToLower())
{
SendMessage(proc.MainWindowHandle, (uint)Message, IntPtr.Zero, IntPtr.Zero);
}
}
That way no variable will refernce the "GetProcesses" and the GC would eventually handle it. 这样,没有变量会引用“GetProcesses”,GC最终会处理它。
变量proc
是foreach循环的本地变量,因此一旦循环完成,它将自动被垃圾收集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.