All rules
CA1837Performance Enabled by default: As suggestion

Use Environment.ProcessId instead of Process.GetCurrentProcess().Id

Use Environment.ProcessId instead of Process.GetCurrentProcess().Id

Microsoft docs

Description

System.Diagnostics.Process.GetCurrentProcess().Id is expensive:

  • It allocates a System.Diagnostics.Process instance, usually just to get the Id.
  • The System.Diagnostics.Process instance needs to be disposed, which has a performance impact.
  • It's easy to forget to call System.Diagnostics.Process.Dispose on the System.Diagnostics.Process instance.
  • If nothing else besides Id uses the Process 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. Rule CA1837 is available starting on .NET 5.0.

Cause

This rule locates calls to System.Diagnostics.Process.GetCurrentProcess().Id and suggests using System.Environment.ProcessId instead, because it is more efficient.

How to fix violations

The violation can either be fixed manually, or, in some cases, using Quick Actions to fix code in Visual Studio.

The following two code snippets show a violation of the rule and how to fix it: A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press <kbd>Ctrl</kbd>+<kbd>.</kbd> (period). Choose Use 'Environment.ProcessId' instead of 'Process.GetCurrentProcess().Id' from the list of options that's presented. !Code fix for CA1837 - Use 'Environment.ProcessId' instead of 'Process.GetCurrentProcess().Id'

Example

using System.Diagnostics;

class MyClass
{
    void MyMethod()
    {
        int pid = Process.GetCurrentProcess().Id;
    }
}

When to suppress

It's safe to suppress a violation of this rule if you're not concerned about the performance impact from unnecessary allocation and eventual disposal of a System.Diagnostics.Process instance.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0