开发者

How to get the current ProcessID?

开发者 https://www.devze.com 2023-01-03 07:21 出处:网络
What\'s the simplest way to obtain th开发者_如何学编程e current process ID from within your own application, using the .NET Framework?Get a reference to the current process and use System.Diagnostics\

What's the simplest way to obtain th开发者_如何学编程e current process ID from within your own application, using the .NET Framework?


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

int nProcessID = Process.GetCurrentProcess().Id;


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.


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消