/// <summary> /// Creates a MemorySnapshot instance for the specified OS process. /// </summary> /// <param name="processId">The ID of the process for which to generate the memory snapshot.</param> /// <returns>A MemorySnapshot instance containing memory information for the specified process, /// at the time of the snapshot.</returns> public static MemorySnapshot FromProcess(int processId) { MemorySnapshot memorySnapshot = new MemorySnapshot(); Process process = Process.GetProcessById(processId); process.Refresh(); PROCESS_MEMORY_COUNTERS_EX counters = MemoryInterop.GetCounters(process.Handle); // Populate memory statistics. memorySnapshot.GdiObjectCount = NativeMethods.GetGuiResources(process.Handle, NativeMethods.GR_GDIOBJECTS); memorySnapshot.HandleCount = process.HandleCount; memorySnapshot.PageFileBytes = counters.PagefileUsage; memorySnapshot.PageFilePeakBytes = counters.PeakPagefileUsage; memorySnapshot.PoolNonpagedBytes = counters.QuotaNonPagedPoolUsage; memorySnapshot.PoolPagedBytes = counters.QuotaPagedPoolUsage; memorySnapshot.ThreadCount = process.Threads.Count; memorySnapshot.UserObjectCount = NativeMethods.GetGuiResources(process.Handle, NativeMethods.GR_USEROBJECTS); memorySnapshot.VirtualMemoryBytes = process.VirtualMemorySize64; memorySnapshot.VirtualMemoryPrivateBytes = counters.PrivateUsage; memorySnapshot.WorkingSetBytes = process.WorkingSet64; memorySnapshot.WorkingSetPeakBytes = process.PeakWorkingSet64; memorySnapshot.WorkingSetPrivateBytes = MemoryInterop.GetPrivateWorkingSet(process); memorySnapshot.Timestamp = DateTime.Now; return(memorySnapshot); }
internal static PROCESS_MEMORY_COUNTERS_EX GetCounters(IntPtr hProcess) { PROCESS_MEMORY_COUNTERS_EX counters = new PROCESS_MEMORY_COUNTERS_EX(); counters.cb = Marshal.SizeOf(counters); if (NativeMethods.GetProcessMemoryInfo(hProcess, out counters, Marshal.SizeOf(counters)) == 0) { throw new Win32Exception(); } return(counters); }
internal static PROCESS_MEMORY_COUNTERS_EX GetCounters(IntPtr hProcess) { PROCESS_MEMORY_COUNTERS_EX counters = new PROCESS_MEMORY_COUNTERS_EX(); counters.cb = Marshal.SizeOf(counters); if (NativeMethods.GetProcessMemoryInfo(hProcess, out counters, counters.cb) == 0) { int error = NativeMethods.GetLastError(); throw new Win32Exception( "GetProcessMemoryInfo failed with last error " + error.ToString() + ": " + "Marshal.SizeOf(counters) = " + Marshal.SizeOf(counters).ToString() + ", " + "counters.cb = " + counters.cb.ToString()); } return(counters); }
static extern int GetProcessMemoryInfo(IntPtr hProcess, out PROCESS_MEMORY_COUNTERS_EX counters, int size);