Process.GetProcesses内存泄漏

时间:2018-11-26 19:56:15

标签: c# memory-leaks process

我正在使用Process.GetProcesses()在本地计算机上获取所有正在运行的进程,但是我猜我存在内存泄漏问题。

那是检索我的进程列表的代码:

List<Process> allProcess = Process.GetProcesses().Where((process) =>
{
    try
    {
        return process.GetMainModuleFileName().Contains("NAME") && !Native.IsResponding(process);
    }
    catch
    {
        return false;
    }
}).ToList();

扩展名GetModuleFileName(返回与架构无关的文件路径)

public static string GetMainModuleFileName(this Process process, int buffer = 1024)
{
    var fileNameBuilder = new StringBuilder(buffer);
    uint bufferLength = (uint)fileNameBuilder.Capacity + 1;
    return QueryFullProcessImageName(process.Handle, 0, fileNameBuilder, ref bufferLength) ?
        fileNameBuilder.ToString() :
        null;
}

IsResponding函数

public static bool IsResponding(Process process)
{
    HandleRef handleRef = new HandleRef(process, process.MainWindowHandle);
    int timeout = 2000;

    IntPtr lResult = SendMessageTimeout(
        handleRef,
        0,
        IntPtr.Zero,
        IntPtr.Zero,
        SMTO_ABORTIFHUNG,
        timeout,
        out IntPtr lpdwResult);

    return lResult != IntPtr.Zero;
}

[DllImport("user32.dll", CharSet=CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
    HandleRef hWnd, 
    int msg, 
    IntPtr wParam, 
    IntPtr lParam, 
    int flags, 
    int timeout, 
    out IntPtr pdwResult);
[DllImport("Kernel32.dll")]
private static extern bool QueryFullProcessImageName([In] IntPtr hProcess, [In] uint dwFlags, [Out] StringBuilder lpExeName, [In, Out] ref uint lpdwSize);

allProcess填满任何结果时,我的应用程序内存就会增加一点,而不会减少。我已经尝试过:

for(int i = allProcess.Count - 1; i >= 0; i--)
{
    allProcess[i].Dispose();
    allProcess[i] = null;
}

allProcess = null;

GC.Collect();
Native.CloseSharedResources();


public static void CloseSharedResources()
{
    PerformanceCounterPermission performanceCounterPermission = new PerformanceCounterPermission(PerformanceCounterPermissionAccess.Read, ".", "*");
    performanceCounterPermission.Demand();
}

仅供测试,当我卸下Process.GetProcesses()时,内存保持稳定。 为什么记忆力永不减少?

0 个答案:

没有答案