windows phone 开发--模拟器调试实时监测内存

方便开发人员监测应用运行内存使用状况,开启后会在模拟器右侧显示实时数据
 
 
一、新建工具类
  public static class MemoryDiagnosticsHelper
  {
    static Popup popup;
    static TextBlock currentMemoryBlock;
    static DispatcherTimer timer;
    static bool forceGc;
 
    public static void Start(bool forceGc)
    {
      MemoryDiagnosticsHelper.forceGc = forceGc;
 
      CreatePopup();
      CreateTimer();
      ShowPopup();
      StartTimer();
    }
 
    private static void ShowPopup()
    {
      popup.IsOpen = true;
    }
 
    private static void StartTimer()
    {
      timer.Start();
    }
 
    private static void CreateTimer()
    {
      if (timer != null)
        return;
 
      timer = new DispatcherTimer();
      timer.Interval = TimeSpan.FromMilliseconds(300);
      timer.Tick += new EventHandler(timer_Tick);
    }
 
    static void timer_Tick(object sender, EventArgs e)
    {
      if (forceGc)
        GC.Collect();
 
      long mem = (long)DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage");
      currentMemoryBlock.Text = string.Format("{0:N}", mem / 1024);
    }
 
    private static void CreatePopup()
    {
      if (popup != null)
        return;
 
      popup = new Popup();
      double fontSize = (double)App.Current.Resources["PhoneFontSizeSmall"] - 2;
      Brush foreground = (Brush)App.Current.Resources["PhoneForegroundBrush"];
      StackPanel sp = new StackPanel { Orientation = Orientation.Horizontal, Background = (Brush)App.Current.Resources["PhoneSemitransparentBrush"] };
      currentMemoryBlock = new TextBlock { Text = "---", FontSize = fontSize, Foreground = foreground };
      sp.Children.Add(new TextBlock { Text = "Mem(k): ", FontSize = fontSize, Foreground = foreground });
      sp.Children.Add(currentMemoryBlock);
      sp.RenderTransform = new CompositeTransform { Rotation = 90, TranslateX = 480, TranslateY = 420, CenterX = 0, CenterY = 0 };
      popup.Child = sp;
    }
 
    public static void Stop()
    {
      HidePopup();
      StopTimer();
    }
 
    private static void StopTimer()
    {
      timer.Stop();
    }
 
    private static void HidePopup()
    {
      popup.IsOpen = false;
    }
  }
 
二、在应用初始化时开启监测
App.cs中
 public App()
    {     
#if DEBUG
      // Display the current frame rate counters.
      Application.Current.Host.Settings.EnableFrameRateCounter = true;
      MemoryDiagnosticsHelper.Start(true);
#endif
}
posted @ 2013-02-18 14:39  zhaowh  阅读(205)  评论(0编辑  收藏  举报