출처 : http://stackoverflow.com/questions/10027341/c-sharp-get-used-memory-in#10028263
서버 모니터링을 해보고 싶어서 메모리 체크하는 부분을 찾아봤는데,
생각보다 잘 안보이더라...
근데 찾았당~
아래와 같은 클래스를 붙여놓고...
//메모리 체크
public static class PerformanceInfo
{
[DllImport("psapi.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetPerformanceInfo([Out] out PerformanceInformation PerformanceInformation, [In] int Size);
[StructLayout(LayoutKind.Sequential)]
public struct PerformanceInformation
{
public int Size;
public IntPtr CommitTotal;
public IntPtr CommitLimit;
public IntPtr CommitPeak;
public IntPtr PhysicalTotal;
public IntPtr PhysicalAvailable;
public IntPtr SystemCache;
public IntPtr KernelTotal;
public IntPtr KernelPaged;
public IntPtr KernelNonPaged;
public IntPtr PageSize;
public int HandlesCount;
public int ProcessCount;
public int ThreadCount;
}
public static Int64 GetPhysicalAvailableMemoryInMiB()
{
PerformanceInformation pi = new PerformanceInformation();
if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi)))
{
return Convert.ToInt64((pi.PhysicalAvailable.ToInt64() * pi.PageSize.ToInt64() / 1048576));
}
else
{
return -1;
}
}
public static Int64 GetTotalMemoryInMiB()
{
PerformanceInformation pi = new PerformanceInformation();
if (GetPerformanceInfo(out pi, Marshal.SizeOf(pi)))
{
return Convert.ToInt64((pi.PhysicalTotal.ToInt64() * pi.PageSize.ToInt64() / 1048576));
}
else
{
return -1;
}
}
}
아래와 같이 사용할 수 있다.
Int64 phav = PerformanceInfo.GetPhysicalAvailableMemoryInMiB();
Int64 tot = PerformanceInfo.GetTotalMemoryInMiB();
decimal percentFree = ((decimal)phav / (decimal)tot) * 100;
decimal percentOccupied = 100 - percentFree;
Console.WriteLine("Available Physical Memory (MiB) " + phav.ToString());
Console.WriteLine("Total Memory (MiB) " + tot.ToString());
Console.WriteLine("Free (%) " + percentFree.ToString());
Console.WriteLine("Occupied (%) " + percentOccupied.ToString());
Console.ReadLine();