Win32异常:"Access is denied"当尝试在Process.GetProcesses

本文关键字:quot GetProcesses Process is 异常 Access Win32 denied | 更新日期: 2023-09-27 18:10:54

我试图执行下面的代码按优先级对正在运行的进程进行分组,我在linq查询的group by子句中得到Win32异常("访问被拒绝")。我以管理员权限在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);
    }
}

Win32异常:"Access is denied"当尝试在Process.GetProcesses

不能访问所有进程的PriorityClass。我会写

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

,称其为

group process by GetPriority(process) into priorityGroup

有些进程会抛出异常,如"System"answers"Idle",这是一个安全设计,其他时候是当你运行32位进程并试图访问64位时,所以为了避免这些异常,我们将过滤掉那些有异常的,1可能的方式如下:

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);
     }
}

我把事情写得很清楚,这样你就知道发生了什么