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 an independent developer focusing on data and business layers, language constructs, parallelism and databases. Specifically Entity Framework, asynchronous and parallel programming, cloud and Azure. He's Microsoft Most Valuable Professional and you can read his articles, guides, tips and tricks at www.tabsoverspaces.com.