通过PID获取进程并监视内存使用情况

时间:2014-05-01 10:56:07

标签: c#

我在监视应用程序的内存使用情况时遇到了一些麻烦。我已经有了一些按名称获取进程的代码。但是可以有多个具有相同名称的进程。因此它只会监视列表中的第一个进程。所以我试图通过PID来获取它。但是我没有可行的代码..但是这就是我在名字命名时使用的内容:

private void SetMemory()
    {
        PerformanceCounter performanceCounter = new PerformanceCounter
        {
            CategoryName = "Process",
            CounterName = "Working Set",
            InstanceName = MinecraftProcess.Process.ProcessName
        };
        try
        {
            string text = ((uint)performanceCounter.NextValue() / 1024 / 1000).ToString("N0") + " MB";
            MemoryValue.Text = text;
            radProgressBar1.Value1 = ((int)performanceCounter.NextValue() / 1024 / 1000);
        }
        catch (Exception ex)
        {

        }
    }

编辑: 我有PID。但我不知道如何开始监测。

2 个答案:

答案 0 :(得分:3)

我不明白你为什么会让事情变得复杂。您可以按如下方式轻松获取进程的内存使用情况:

int pid = your pid;
Process toMonitor = Process.GetProcessById(pid);
long memoryUsed = toMonitor.WorkingSet64;

此属性返回工作集中页面使用的内存(以字节为单位)。

答案 1 :(得分:0)

您有很多可能不断观察过程的记忆消耗。其中一个是(例如,如果你没有UI应用程序)来启动task(使用.NET Task Parallel Library),那就是连续轮询内存消耗。第一步是获取进程(按名称或by PID并获取当前内存使用情况。最简单的方法是@Jurgen Camilleri建议:

private void checkMemory(Process process)
{
    try
    {           
        if (process != null)
        {
            Console.WriteLine("Memory Usage: {0} MB", process.WorkingSet64 / 1024 / 1024);
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception.Message);
    }
}

使用 WorkingSet(64)是与任务管理器内存使用情况最接近的信息(您可以这么简单)。轮询代码:

var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
// take the first firefox instance once; if you know the PID you can use Process.GetProcessById(PID);
var firefox = Process.GetProcessesByName("firefox").FirstOrDefault();
var timer = new System.Threading.Tasks.Task(() =>
{
    cancellationToken.ThrowIfCancellationRequested();
    // poll
    while (true)
    {
        checkMemory(firefox);
        // we want to exit
        if (cancellationToken.IsCancellationRequested)
        {
            cancellationToken.ThrowIfCancellationRequested();
        }
        // give the system some time
        System.Threading.Thread.Sleep(1000);
    }
}, cancellationToken);
// start the polling task
timer.Start();
// poll for 2,5 seconds
System.Threading.Thread.Sleep(2500);
// stop polling
cancellationTokenSource.Cancel();

如果你有一个正在运行的Windows窗体/ WPF应用程序,你可以使用例如定时器(及其回调方法,例如System.Threading.Timer class)而不是任务来轮询某些指定的内存使用情况间隔。