94

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

Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306
plaureano
  • 3,060
  • 5
  • 29
  • 29

3 Answers3

133

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

int nProcessID = Process.GetCurrentProcess().Id;
Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306
luvieere
  • 36,324
  • 18
  • 123
  • 178
  • 2
    using System.Diagnostics; or System.Diagnostics.Process.GetCurrentProcess().Id; I always protect myself and assume that current or future policy rules will restrict this call in some locked down or restrictive mode because it access the process areas. – Sql Surfer Jul 31 '16 at 14:29
18
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;
Joe
  • 118,426
  • 28
  • 194
  • 329
17

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.

ckuri
  • 3,160
  • 2
  • 13
  • 17