.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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 14:23:13  来源:igfitidea点击:

How to get the current ProcessID?

.netprocess

提问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.DiagnosticsProcess.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;