How to get the current ProcessID?

.NetProcess

.Net Problem Overview


What's the simplest way to obtain the current process ID from within your own application, using the .NET Framework?

.Net Solutions


Solution 1 - .Net

Get a reference to the current process and use System.Diagnostics's Process.Id property:

int nProcessID = Process.GetCurrentProcess().Id;

Solution 2 - .Net

Process.GetCurrentProcess().Id

Or, since the Process class is IDisposable, and the Process ID isn't going to change while your application's running, you could have a helper class with a static property:

public static int ProcessId
{
	get 
	{
		if (_processId == null)
		{
			using(var thisProcess = System.Diagnostics.Process.GetCurrentProcess())
			{
				_processId = thisProcess.Id;
			}
		}
		return _processId.Value;
	}
}
private static int? _processId;

Solution 3 - .Net

The upcoming .NET 5 introduces Environment.ProcessId which should be preferred over Process.GetCurrentProcess().Id as it avoids allocations and the need to dispose the Process object.

https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-5/ shows a benchmark where Environment.ProcessId only takes 3ns instead of 68ns with Process.GetCurrentProcess().Id.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionplaureanoView Question on Stackoverflow
Solution 1 - .NetluvieereView Answer on Stackoverflow
Solution 2 - .NetJoeView Answer on Stackoverflow
Solution 3 - .NetckuriView Answer on Stackoverflow