Pattern: Use of Process.GetCurrentProcess().Id
Issue: -
System.Diagnostics.Process.GetCurrentProcess().Id
is expensive:
- It allocates a
Process
instance, usually just to get theId
. - The
Process
instance needs to be disposed, which has a performance impact. - It's easy to forget to call
Dispose()
on theProcess
instance. - If nothing else besides
Id
uses theProcess
instance, then the linked size grows unnecessarily by increasing the graph of types referenced. - It is somewhat difficult to discover or find this API.
System.Environment.ProcessId
avoids all the above.
Example of incorrect code:
int pid = Process.GetCurrentProcess().Id;
Example of correct code:
int pid = System.Environment.ProcessId;