2012-12-13 42 views
0

我希望使一個Listener能夠監視/跟蹤RAM的使用情況。讓一個Listerner來檢測內存使用情況

我知道,在C#中,我們可以使用

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; 
     } 

     } 
    } 
    }  

沒有這個監聽器應該跟蹤RAM使用的每一秒,如果它比指定%年齡越大,那麼它應該Kill Some Processes還是應該提供一些獲得工作用法通知我的應用程序(WPF應用程序)殺死一些特定的進程

怎樣才能讓一段代碼constantlr聽SYTEM,然後調用一些動作

在這方面的任何幫助將是巨大的..

回答

0

用於定時器類。像System.Timers.Timer甚至簡單的Thread.Sleep(1000)都可以(假設你的代碼在非UI線程上分開運行)。