2019-9-2-dotnet-获取当前进程方法

title author date CreateTime categories
dotnet 获取当前进程方法
lindexi
2019-9-2 11:3:3 +0800
2019-09-02 10:59:36 +0800
dotnet

本文告诉大家如何在 dotnet 程序获取当前进程

使用下面代码可以获取当前进程

var process = Process.GetCurrentProcess();

那么这个方法的性能如何?

这个获取的方法内部有缓存,第一次获取的速度会比较慢,稍后会比较快,我使用下面代码测量

            var stopwatch = new Stopwatch();

            for (int i = 0; i < 100; i++)
            {
                stopwatch.Restart();

                var process = Process.GetCurrentProcess();
                stopwatch.Stop();

                Console.WriteLine(stopwatch.ElapsedTicks);
            }

第一次运行的时候比较长,稍后运行速度会快很多

908
161
25
15
14
17
15
15
18
20
// 忽略

如果只是想要拿到进程号可以使用下面代码

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern int GetCurrentProcessId();

使用上面代码获取的性能能更快,但第一次获取的速度也不快

如果是在循环或其他代码里面,建议将进程号缓存起来

原文地址:https://www.cnblogs.com/lindexi/p/12086226.html