tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

New Environment.ProcessId in .NET 5

4 Nov 2020 1 mins .NET

While reading some code in .NET runtime, I found Environment.ProcessId property, which surprised me a bit, because I had no idea it existed. Quick look into the documentation and no wonder I had no idea. It’s new in .NET 5.

If you wanted to get process id of current process, the easiest way, same way all the way back to stone age days of .NET, was Process.GetCurrentProcess().Id. And there’s nothing wrong with it, but creating a whole Process class instance to get just the process id is little bit overkill.

With .NET 5 you can use the new Environment.ProcessId, which in turn uses interop call into OS and caches the value. Because as long as the process is running the process id is set, so why not, right? Not creating the instance wastefully and also caching the value is great performance benefit.

Added to, even if you use the GetCurrentProcess, you’ll get the benefit of caching, because the Environment.ProcessId is used there.

The “inner” implementation is the same as was before (at least recent “before”). I.e. on Windows it calls unchecked((int)Interop.Kernel32.GetCurrentProcessId()) or on Linux Interop.Sys.GetPid();. The GetPid, to pick one, calls getpid via SystemNative_GetPid. Nothing unordinary.

I like these “small and hidden” improvements, maybe even more than the “big and flashy” ones.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.