Reputation: 305
I am trying to execute the below code to group the running processes by priority and I get a Win32 exception ("Access is denied") at the linq query's group by clause. I ran this code in VS2010 with administrator privilege.
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);
}
}
Upvotes: 1
Views: 1189
Reputation: 4542
Some process will throw that exception like "System" and "Idle",its a security design,other times is when your running a 32bit process and trying to access a 64bit,so to avoid those exceptions we will filter out those that have exceptions,1 possible way like this:
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);
}
}
I left things very explicit so you know whats happening.
Upvotes: 2
Reputation: 15364
You can not access PriorityClass of all processes. I would write
ProcessPriorityClass GetPriority(Process p)
{
try{
return p.PriorityClass;
}catch{
return (ProcessPriorityClass)0;
}
}
and call it as
group process by GetPriority(process) into priorityGroup
Upvotes: 2