.net 如何获取当前的ProcessID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3003975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the current ProcessID?
提问by plaureano
What's the simplest way to obtain the current process ID from within your own application, using the .NET Framework?
使用 .NET Framework 从您自己的应用程序中获取当前进程 ID 的最简单方法是什么?
回答by luvieere
Get a reference to the current process and use System.Diagnostics's Process.Idproperty:
获取对当前进程的引用并使用System.Diagnostics的Process.Id属性:
int nProcessID = Process.GetCurrentProcess().Id;
回答by Joe
Process.GetCurrentProcess().Id
Or, since the Processclass 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:
或者,由于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;

