Win32异常:"访问被拒绝"尝试在Process.GetProcesses()上执行LINQ查询时

时间:2014-06-29 15:20:03

标签: c# linq process

我正在尝试执行以下代码以按优先级对正在运行的进程进行分组,并在linq查询的group by子句中获得Win32异常(" Access被拒绝")。我使用管理员权限在VS2010中运行此代码。

var processesList = Process.GetProcesses();
var processQuerySet = from process in processesList
                      group process by process.PriorityClass into priorityGroup
                      select priorityGroup;           
foreach (var priority in processQuerySet)
{
    Console.WriteLine(priority.Key.ToString());
    foreach (var process in priority)
    {
        Console.WriteLine("\t{0}   {1}", process.ProcessName, process.WorkingSet64);
    }
}

2 个答案:

答案 0 :(得分:2)

您无法访问所有进程的PriorityClass。我会写

ProcessPriorityClass GetPriority(Process p)
{
    try{
        return p.PriorityClass;
    }catch{
        return (ProcessPriorityClass)0;
    }
}

并将其命名为

group process by GetPriority(process) into priorityGroup

答案 1 :(得分:2)

某些进程会抛出异常,例如" System"和#34; Idle",它是一个安全设计,有时候是你运行32位进程并尝试访问64位,所以为了避免这些异常,我们将过滤掉那些有异常的,这样的可能方式:

Dictionary<string, List<Process>> procs = new Dictionary<string, List<Process>>()
{
    {"With Exception",new List<Process>()},
    {"Without Exception",new List<Process>()}
};

foreach (var proc in Process.GetProcesses())
{
    Exception ex = null;
    try
    {
        //based on your example,many other properties will also throw
        ProcessPriorityClass temp = proc.PriorityClass;
    }
    catch (Exception e)
    {
         ex = e;
    }
    finally
    {
         if (ex == null)
             procs["Without Exception"].Add(proc);
         else
             procs["With Exception"].Add(proc);
    }
}

var processQuerySet = from process in procs["Without Exception"]
                      group process by process.PriorityClass into priorityGroup
                      select priorityGroup;

foreach (var priority in processQuerySet)
{
     Console.WriteLine(priority.Key.ToString());
     foreach (var process in priority)
     {
         Console.WriteLine("\t{0}   {1}", process.ProcessName, process.WorkingSet64);
     }
}

我把事情弄得很清楚,所以你知道发生了什么。