Skip to content

Instantly share code, notes, and snippets.

@billzhuang
Created March 31, 2014 08:22
Show Gist options
  • Save billzhuang/9887698 to your computer and use it in GitHub Desktop.
Save billzhuang/9887698 to your computer and use it in GitHub Desktop.
get app domain memory usage
<%@ Page Language="C#" AutoEventWireup="true" ViewStateMode="Disabled" Inherits="System.Web.UI.Page" %>
<%@ Import Namespace="System.Diagnostics" %>
<script runat="server">
//http://stackoverflow.com/questions/2611141/calculate-private-working-set-memory-using-c-sharp
//http://cybernetnews.com/cybernotes-windows-memory-usage-explained/
//http://blogs.technet.com/b/askperf/archive/2010/03/30/perfmon-identifying-processes-by-pid-instead-of-instance.aspx
//http://msdn.microsoft.com/en-us/library/aa965225%28VS.85%29.aspx
protected void Page_Load(object sender, EventArgs e)
{
var os = System.Environment.OSVersion;
var proc = Process.GetCurrentProcess();
if (os.Platform != PlatformID.Win32NT)
{
return;
}
if (os.Version.Major >= 6)
{
// for windows 2008 later server, we get the dedicate memory usage as TaskMgr result
var prcName = GetNameToUseForMemory(proc);
var counter = new PerformanceCounter("Process", "Working Set - Private", prcName);
Response.Write("Private Working Set:" + counter.RawValue / 1024);
}
else
{
// for windows 2003 web server, we just show as TasgMgr same result, it include shared memory
// it's hard to get the private workingSet
Response.Write("Working Set:" + proc.WorkingSet64 / 1024);
}
}
private string GetNameToUseForMemory(Process proc)
{
var nameToUseForMemory = String.Empty;
var category = new PerformanceCounterCategory("Process");
var instanceNames = category.GetInstanceNames().Where(x => x.Contains(proc.ProcessName));
foreach (var instanceName in instanceNames)
{
using (var performanceCounter = new PerformanceCounter("Process", "ID Process", instanceName, true))
{
if (performanceCounter.RawValue != proc.Id)
continue;
nameToUseForMemory = instanceName;
break;
}
}
return nameToUseForMemory;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment