C# 通过PID获取进程并监控内存使用情况
我在监控应用程序的内存使用方面遇到了一点问题。我已经有了一些按名称获取进程的代码。。但是可以有多个同名进程。因此,它将只监视列表中的第一个进程。。所以我试着通过PID得到它。但我没有有效的代码。。但以下是我在点名时使用的:C# 通过PID获取进程并监控内存使用情况,c#,C#,我在监控应用程序的内存使用方面遇到了一点问题。我已经有了一些按名称获取进程的代码。。但是可以有多个同名进程。因此,它将只监视列表中的第一个进程。。所以我试着通过PID得到它。但我没有有效的代码。。但以下是我在点名时使用的: private void SetMemory() { PerformanceCounter performanceCounter = new PerformanceCounter { CategoryName =
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。但我不知道如何从那开始监控。我不明白你为什么要把事情复杂化。您可以按如下方式轻松获取进程的内存使用情况:
int pid = your pid;
Process toMonitor = Process.GetProcessById(pid);
long memoryUsed = toMonitor.WorkingSet64;
此属性以字节为单位返回工作集中的页所使用的内存。您可以随时观察进程的内存消耗情况。其中之一是(例如,如果您没有UI应用程序)启动一个(使用),它将持续轮询内存消耗。第一步是获取进程(按名称或名称),并获取当前内存使用情况。最简单的方法是@Jurgen camileri建议的:
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 forms/WPF应用程序,您可以使用例如计时器(以及它们的回调方法,例如)来代替任务,以便在指定的时间间隔内轮询内存使用情况。为什么不安装ANTS Profiler试用版(14天试用版)。如果您试图识别内存问题,它就是其中之一。@Anthony Horne不试图识别内存问题。。它应该监视服务器(游戏服务器)内存Usage。。我假设您复制/粘贴了这里的代码。ProcessName要做什么?@rene它从我的另一个类获取进程名。@AnthonyHorne process Explorer是免费的。@AnthonyHorne process Explorer(这不是Highlander。)我一直在测试
进程
类,似乎进程.WorkingSet64
(以及其他属性)在后续调用中返回相同的值,因此我猜它从创建对象的那一刻获取读数。因此,似乎必须在每次迭代中执行过程。GetProcessById(pid);
。:(奇怪但无论如何。。。