Skip to content

API Proposal: Add Environment.ProcessId property #38388

@stephentoub

Description

@stephentoub

Background and Motivation

A non-trivial amount of code uses:

Process.GetCurrentProcess().Id

to get the ID of the current process. Some examples:

https://source.dot.net/#System.Diagnostics.Process/System/Diagnostics/Process.cs,e7bdad2b99a54a87,references

While that works:
a) from a throughput perspective it's much more expensive than it needs to be
b) it allocates a Process just to get the Id
c) it's easy to forget to Dispose of the Process instance, making it that much more expensive
d) if nothing else is using Process, it increases linked size by increasing the graph of types referenced
e) it's not as discoverable as it otherwise could be

It'd be nice to have a cheap, simple, available-without-using-Process way to get at the current process' ID, for logging or any other reason.

Various places avoid going through Process by P/Invoking directly; such usage could be switched to this new API.

Proposed API

public static class Environment
{
    public static int ProcessId { get; } // new property
    ...
}

Usage Examples

Log($"{Environment.ProcessId}: {message}");

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Runtimecode-fixerMarks an issue that suggests a Roslyn code fixer

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions