101

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

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
plaureano
  • 3,139
  • 6
  • 30
  • 29

3 Answers3

142

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

int nProcessID = Process.GetCurrentProcess().Id;
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
luvieere
  • 37,065
  • 18
  • 127
  • 179
  • 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
31

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,784
  • 2
  • 15
  • 17
  • Seems reasonable to prefer `Environment.ProcessId` simply because it's more concise. But you've got me wondering what kind of application would be running this so frequently that an additional 65ns would ever add up to anything that mattered. – BVernon Jan 15 '23 at 07:03
  • 2
    @BVernon The saved 65 isn’t all. You should also dispose the Process instance. A Process instance also runs a finalizer which takes additional (GC) time, and each Process instance has (a small) memory footprint. The [original intention](https://github.com/dotnet/runtime/issues/38388) was to improve logging, where you would often also log the process Id for every log message to differentiate the log source in case your logging sink receives logs from different processes. If you have same very fine-grained logging you don’t want to have a finalizable object created each time. – ckuri Jan 15 '23 at 12:21
  • Makes sense. Thanks for sharing the additional detail. – BVernon Jan 18 '23 at 07:46
23
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
  • 122,218
  • 32
  • 205
  • 338
  • This one should be marked as the answer as it highlights the fact that GetCurrentProcess() returns a "Process" object which must be disposed in order to avoid leaks. – gio Aug 11 '22 at 12:11