简体   繁体   English

Windows XP的.NET Process问题

[英].NET Process issues with Windows XP

First off, I am using my own Process Wrapper to hold the starting path of a process. 首先,我使用自己的Process Wrapper来保存进程的起始路径。

public class MCProcess()
{
       public Process Process { get; set;}
       public string  StartingPath { get; set;}

       public MCProcess(string start, Process p)
       {
             Process = p;
             StartingPath = start;
       }
}

Now, I keep have a List<MCProcces> called runningProcesses that I use to keep track of all the processes and starting paths of every process that my program has started. 现在,我保留了一个名为runningProcesses的List<MCProcces> ,用于跟踪程序已启动的所有进程和每个进程的启动路径。

For Example: 例如:

string path = "C:\\Windows\\System32\\notepad.exe";
Process temp = Process.Start(path);
runningProcesses.Add(new MCProcess(path, temp));

Now, sometimes, I want to close processes that I have run. 现在,有时,我想关闭已运行的进程。 Instead of looking through the task manager and trying to find the MainModuleName of each process that I started, I included the StartingPath for a reason. 而不是浏览任务管理器并尝试查找我启动的每个进程的MainModuleName,而是出于某种原因而包含了StartingPath。

If I want to close a notepad, I just loop through my runningProcesses, find out which process has the startingPath for notepad and then use Process.Kill to kill that process. 如果要关闭记事本,则只需遍历runningProcesses,找出哪个进程具有记事本的startingPath,然后使用Process.Kill终止该进程。

string path = "C:\\Windows\\System32\\notepad.exe";
for (int i = 0; i < runningProcesses.Count; i++)
{
     if (runningProcesses[i].StartingPath == path)
     {
          runningProcesses[i].Process.Kill();
          runningProcesses.RemoveAt(i);
     }
}

This code works beautiful on Windows 7 and I have had no issues at all. 该代码在Windows 7上可以正常运行,我一点也没有问题。 However, when using this on Windows XP, I get an ArgumentNullException with Process.Kill. 但是,在Windows XP上使用它时,我得到了带有Process.Kill的ArgumentNullException。

Is there something about the Process class that doesn't make it work well on Windows XP? 关于Process类,在Windows XP上无法正常工作吗?

Amazed how this is working in win 7. You are modifying a collection while using it in loop. 惊讶于win 7中它是如何工作的。您正在循环使用它时修改了一个集合。 You should maintain index of processes to be deleted, and then once done with the loop, remove all the processes 您应该维护要删除的进程的索引,然后完成循环,然后删除所有进程

Try something like 尝试类似

var processesToRemove = runningProcesses.Where (p => String.Equals(p.StartingPath, path);
foreach(var process in processToRemove)
{
  process.Process.Kill();
  runningProcesses.Remove(process);
}

Try making your properties public: 尝试将您的媒体资源公开:

Public Process Process { get; set;}
Public string  StartingPath { get; set;}

Then kill your process like this: 然后像这样终止您的进程:

for (int i = 0; i < runningProcesses.Count; i++)
{
    if (runningProcesses[i].StartingPath == path)
    {
          runningProcesses[i].Process.Kill();
    }
}

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

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