我需要担心 foreach 循环中的 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);
}
}
提前致谢, 戒日
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.
//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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为了确保尽早释放所有资源,请在不再需要该进程时调用 Dispose。
To make sure all resoucers are freed as early as possible, call Dispose on the process, when you no longer need it.
一般来说,您无需担心对象的处置或解除分配,除非该对象实现了
IDisposable
接口。如果确实如此,您应该在完成后手动调用它的Dispose()
方法,或者用using
语句包装以自动调用它:In general terms you don't need to worry about disposing or deallocating objects, unless the object implements the
IDisposable
interface. If it does you should either call theDispose()
method on it manually when you're finished, or wrap with ausing
statement to have it called automatically:如果您正在循环查找您赢得的进程,那么您可以尝试类似的操作:
无论如何,我会将其更改为:
这样就没有变量会引用“GetProcesses”,并且 GC 最终会处理它。
IF you are looping to find your won process then you could try something like:
In any case I would change it to:
That way no variable will refernce the "GetProcesses" and the GC would eventually handle it.
变量 proc 是 foreach 循环的本地变量,因此一旦循环完成,它将自动被垃圾收集。
The variable
proc
is local to the foreach loop so once the loop completes, it will automatically be garbage collected.