Reputation: 43
What I'm trying to do is get the processing time per process using a method
//Current Method
public string GetRunningTime(Process p){
string returnString = "00:00:00:00.00";//DD:HH;MM;SS.ff
try{
returnString = DateTime.Now.Subtract(p.StartTime).ToString(@"dd\.hh\:mm\:ss\.ff");//Time now - StartTime. ToString With format
}catch(Exception){}//Catchs System.ComponentModel.Win32Exception: 'Access is denied'
return returnString;//returns the string.
}
And the try-catch is the only way I could do the math without crashing. I was wondering if there is a way to know if the program has access to view the StartTime. so it would know not to do the math.
//Example Method
public string GetRunningTime(Process p){
string returnString = "00:00:00:00.00";
if(p.HasAcessToStartTime){//Trying to immitate
returnString = DateTime.Now.Subtract(p.StartTime).ToString(@"dd\.hh\:mm\:ss\.ff");
}
return returnString;
}
Upvotes: 3
Views: 646
Reputation: 22251
There is no generalized means to check whether you can access process information, because each process can have a different discretionary access list. The appropriate means to check whether you can access the information is to attempt to access the information. Even if such a check did exist, it opens a TOCTOU error if the DACL is changed between check and access.
If your concern is regarding the "cost" of exception handling, then you should profile the application to verify that cost. In most cases, exception handling is not the real performance problem.
If you were for some reason running this code in a tight loop, and you really needed to avoid the cost of throwing exceptions, you can call GetProcessTimes
directly, which would return zero in the event of an error. But if you are calling this in a tight loop, consider... not doing that. This seems like information that could be readily cached.
Upvotes: 0
Reputation: 8330
According to the official documentation, the StartTime
shows you if something is wrong only via Exceptions.
NotSupportedException
You are attempting to access the StartTime property for a process that is running on a remote computer. This property is available only for processes that are running on the local computer.
InvalidOperationException
The process has exited.
OR
The process has not been started.
Win32Exception
An error occurred in the call to the Windows function.
There are a few options available to explain the problem:
64-bit
process from 32-bit
.svchost
system process) as mentioned in this answer may behave that way.Upvotes: 3