C#idiomatic C#
ca1837fundamentals/code-analysis/quality-rules

Code analysis

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

Learn about code analysis rule CA1837: Use 'Environment.ProcessId' instead of 'Process.GetCurrentProcess().Id'

CA1837 Performance enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

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

Rule description

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

System.Environment.ProcessId avoids all the above.

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:

csharp
using System.Diagnostics;

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

Class MyClass
    Private Sub MyMethod()
        Dim pid As Integer = Process.GetCurrentProcess().Id
    End Function
End Class
csharp
using System.Diagnostics;

class MyClass
{
    void MyMethod()
    {
        int pid = System.Environment.ProcessId;
    }
}
vb
Imports System.Diagnostics

Class MyClass
    Private Sub MyMethod()
        Dim pid As Integer = System.Environment.ProcessId
    End Function
End Class

When to suppress warnings

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.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

csharp
#pragma warning disable CA1837
// The code that's violating the rule is on this line.
#pragma warning restore CA1837

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_diagnostic.CA1837.severity = none

For more information, see How to suppress code analysis warnings.

See also