使用.NET框架,从你的应用程序内部获取当前进程ID的最简单方法是什么?
获取当前进程的引用,使用System.Diagnostics
的Process.Id
属性:
int nProcessID = Process.GetCurrentProcess().Id;
Environment.ProcessId
,应该优先使用它而不是 Process.GetCurrentProcess().Id
,因为它避免了分配内存和处理过程对象的需要。
https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-5/ 显示,在一个基准测试中,Environment.ProcessId
只需要 3ns,而 Process.GetCurrentProcess().Id
则需要 68ns。Environment.ProcessId
是合理的,因为它更简洁。但是您让我想知道会有什么类型的应用程序频繁运行这个,以至于额外的65纳秒会和任何相关重要事项相加。 - BVernonProcess.GetCurrentProcess().Id
或者,由于Process
类是IDisposable
的,而进程ID在应用程序运行时不会改变,因此您可以使用具有静态属性的辅助类:
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;