public static class MemoryDiagnosticsHelper
{
public static bool isStart = false;
static Popup popup;
static TextBlock currentMemoryKB;
static TextBlock currentMemoryMB;
static TextBlock currentLumitMemoryMB;
static DispatcherTimer timer;
static bool forceGc;
const long MAX_MEMORY = 90 * 1024 * 1024; // 90MB, per marketplace
static int lastSafetyBand = -1; // to avoid needless changes of colour const long MAX_CHECKPOINTS = 10; // adjust as needed
static Queue<MemoryCheckpoint> recentCheckpoints; static bool alreadyFailedPeak = false; // to avoid endless Asserts /// <summary>
/// Starts the memory diagnostic timer and shows the counter
/// </summary>
/// <param name="timespan">The timespan between counter updates</param>
/// <param name="forceGc">Whether or not to force a GC before collecting memory stats</param>
[Conditional("DEBUG")]
public static void Start(TimeSpan timespan, bool forceGc)
{
isStart = true;
if (timer != null) throw new InvalidOperationException("Diagnostics already running"); MemoryDiagnosticsHelper.forceGc = forceGc;
recentCheckpoints = new Queue<MemoryCheckpoint>(); StartTimer(timespan);
ShowPopup();
} /// <summary>
/// Stops the timer and hides the counter
/// </summary>
[Conditional("DEBUG")]
public static void Stop()
{
isStart = false;
HidePopup();
StopTimer();
recentCheckpoints = null;
} /// <summary>
/// Add a checkpoint to the system to help diagnose failures. Ignored in retail mode
/// </summary>
/// <param name="text">Text to describe the most recent thing that happened</param>
[Conditional("DEBUG")]
public static void Checkpoint(string text)
{
if (recentCheckpoints == null) return;
if (recentCheckpoints.Count >= MAX_CHECKPOINTS - 1) recentCheckpoints.Dequeue();
recentCheckpoints.Enqueue(new MemoryCheckpoint(text, GetCurrentMemoryUsage()));
} /// <summary>
/// Recent checkpoints stored by the app; will always be empty in retail mode
/// </summary>
public static IEnumerable<MemoryCheckpoint> RecentCheckpoints
{
get
{
if (recentCheckpoints == null) yield break; foreach (MemoryCheckpoint checkpoint in recentCheckpoints) yield return checkpoint;
}
} /// <summary>
/// Gets the current memory usage, in bytes. Returns zero in non-debug mode
/// </summary>
/// <returns>Current usage</returns>
public static long GetCurrentMemoryUsage()
{
// don't use DeviceExtendedProperties for release builds (requires a capability)
return (long)DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage"); } /// <summary>
/// Gets the current memory usage, in bytes. Returns zero in non-debug mode
/// </summary>
/// <returns>Current usage</returns>
public static long GetCurrentPeakMemoryUsage()
{
// don't use DeviceExtendedProperties for release builds (requires a capability)
return (long)DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage"); } /// <summary>
/// Gets the peak memory usage, in bytes. Returns zero in non-debug mode
/// </summary>
/// <returns>Peak memory usage</returns>
public static long GetPeakMemoryUsage()
{
// don't use DeviceExtendedProperties for release builds (requires a capability)
return (long)DeviceExtendedProperties.GetValue("ApplicationPeakMemoryUsage");
} /// <summary>
/// Gets the peak memory usage, in bytes. Returns zero in non-debug mode
/// </summary>
/// <returns>Peak memory usage</returns>
public static long GetLumitMemoryUsage()
{
// don't use DeviceExtendedProperties for release builds (requires a capability)
return (long)DeviceExtendedProperties.GetValue("ApplicationWorkingSetLimit");
} private static void ShowPopup()
{
popup = new Popup();
double fontSize = (double)Application.Current.Resources["PhoneFontSizeSmall"] - 2;
Brush foreground = (Brush)Application.Current.Resources["PhoneForegroundBrush"];
StackPanel sp = new StackPanel { Orientation = Orientation.Horizontal, Background = (Brush)Application.Current.Resources["PhoneSemitransparentBrush"] };
//currentMemoryKB = new TextBlock { Text = "---", FontSize = fontSize, Foreground = new SolidColorBrush(Colors.Red)};
//peakMemoryBlock = new TextBlock { Text = "", FontSize = fontSize, Foreground = new SolidColorBrush(Colors.White), Margin = new Thickness(5, 0, 0, 0) };
//sp.Children.Add(new TextBlock { Text = " kb", FontSize = fontSize, Foreground = foreground }); //sp.Children.Add(currentMemoryKB); currentMemoryMB = new TextBlock { Text = "---", FontSize = fontSize, Foreground = new SolidColorBrush(Colors.White) };
currentMemoryKB = new TextBlock { Text = "---", Margin = new Thickness(10, 0, 0, 0), FontSize = fontSize, Foreground = new SolidColorBrush(Colors.Red) };
currentLumitMemoryMB = new TextBlock { Text = "---", Margin = new Thickness(10, 0, 0, 0), FontSize = fontSize, Foreground = new SolidColorBrush(Colors.Green) };
sp.Children.Add(currentMemoryMB);
sp.Children.Add(currentMemoryKB);
sp.Children.Add(currentLumitMemoryMB); sp.RenderTransform = new CompositeTransform { Rotation = 0, TranslateX = 150, TranslateY = 0, CenterX = 0, CenterY = 0 };
popup.Child = sp;
popup.IsOpen = true;
} private static void StartTimer(TimeSpan timespan)
{
timer = new DispatcherTimer();
timer.Interval = timespan;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
} static void timer_Tick(object sender, EventArgs e)
{
if (forceGc) GC.Collect(); UpdateCurrentMemoryUsage();
UpdatePeakMemoryUsage(); } private static void UpdatePeakMemoryUsage()
{
if (alreadyFailedPeak) return; long peak = GetPeakMemoryUsage();
//if (peak >= MAX_MEMORY)
//{
// alreadyFailedPeak = true;
// Checkpoint("*MEMORY USAGE FAIL*");
// if (Debugger.IsAttached) Debug.Assert(false, "Peak memory condition violated");
//}
} private static void UpdateCurrentMemoryUsage()
{
try
{
long mem = GetCurrentMemoryUsage();
long feng = GetCurrentPeakMemoryUsage();
long lumit = GetLumitMemoryUsage();
currentMemoryKB.Text = string.Format("{0:f}", feng / 1024.0 / 1024.0) + "MB";
currentMemoryMB.Text = string.Format("{0:f}", mem / 1024.0 / 1024.0) + "MB";
currentLumitMemoryMB.Text = string.Format("{0:f}", lumit / 1024.0 / 1024.0) + "MB";
}
catch { }
//int safetyBand = GetSafetyBand(mem);
//if (safetyBand != lastSafetyBand)
//{
// currentMemoryKB.Foreground = GetBrushForSafetyBand(safetyBand);
// lastSafetyBand = safetyBand;
//}
} private static Brush GetBrushForSafetyBand(int safetyBand)
{
return new SolidColorBrush(Colors.Red);
//switch (safetyBand)
//{
// case 0:
// return new SolidColorBrush(Colors.Green); // case 1:
// return new SolidColorBrush(Colors.Orange); // default:
// return new SolidColorBrush(Colors.Red);
//}
} private static int GetSafetyBand(long mem)
{
double percent = (double)mem / (double)MAX_MEMORY;
if (percent <= 0.75) return 0; if (percent <= 0.90) return 1; return 2;
} private static void StopTimer()
{
timer.Stop();
timer = null;
} private static void HidePopup()
{
popup.IsOpen = false;
popup = null;
}
} /// <summary>
/// Holds checkpoint information for diagnosing memory usage
/// </summary>
public class MemoryCheckpoint
{
/// <summary>
/// Creates a new instance
/// </summary>
/// <param name="text">Text for the checkpoint</param>
/// <param name="memoryUsage">Memory usage at the time of the checkpoint</param>
internal MemoryCheckpoint(string text, long memoryUsage)
{
Text = text;
MemoryUsage = memoryUsage;
} /// <summary>
/// The text associated with this checkpoint
/// </summary>
public string Text { get; private set; } /// <summary>
/// The memory usage at the time of the checkpoint
/// </summary>
public long MemoryUsage { get; private set; }
}
调用方式:
 MemoryDiagnosticsHelper.Start(TimeSpan.FromMilliseconds(500), true);

Windows Phone 8 显示当前项目的使用内存,最大峰值,最大内存上限的更多相关文章

  1. Windows中使用TortoiseGit提交项目到GitLab配置

    下文来给各位介绍Windows中使用TortoiseGit提交项目到GitLab配置过程,下在全部图片希望对各位带来方便面. Gitlab默认的配置推荐使用shell命令行与server端进行交互,作 ...

  2. Git安装配置和提交本地代码至Github,修改GitHub上显示的项目语言

    1. 下载安装git Windows版Git下载地址: https://gitforwindows.org/ 安装没有特别要求可以一路Next即可,安装完成后可以看到: 2. 创建本地代码仓库 打开G ...

  3. 怎么将linux下的项目转换成windows的VS2010下的项目?

    怎么将linux下的项目转换成windows的VS2010下的项目?             不显示删除回复             显示所有回复             显示星级回复        ...

  4. 【转】Windows中使用TortoiseGit提交项目到GitLab配置

    转  原文地址 https://www.cnblogs.com/xiangwengao/p/4134492.html   下文来给各位介绍Windows中使用TortoiseGit提交项目到GitLa ...

  5. [ASP.NET MVC] 使用CLK.AspNet.Identity提供依权限显示选单项目的功能

    [ASP.NET MVC] 使用CLK.AspNet.Identity提供依权限显示选单项目的功能 CLK.AspNet.Identity CLK.AspNet.Identity是一个基于ASP.NE ...

  6. Windows Server 2008 显示桌面图标

    相信有朋友们有安装使用过windows 2008 server服务器,刚安装好的时候,桌面上只有一个回收站的图标,它没有像windows 7或windows 8一样可以直接通过右击鼠标的菜单来设置,要 ...

  7. C#使用Windows API 隐藏/显示 任务栏 (FindWindowEx, ShowWindow)

    原文 C#使用Windows API 隐藏/显示 任务栏 (FindWindowEx, ShowWindow) 今天,有网友询问,如何显示和隐藏任务栏? 我这里,发布一下使用Windows API 显 ...

  8. windows cmd命令显示UTF8设置

    windows cmd命令显示UTF8设置   在中文Windows系统中,如果一个文本文件是UTF-8编码的,那么在CMD.exe命令行窗口(所谓的DOS窗口)中不能正确显示文件中的内容.在默认情况 ...

  9. Jenkins 为Jenkins添加Windows Slave远程执行python项目脚本

    为Jenkins添加Windows Slave远程执行python项目脚本   by:授客 QQ:1033553122 测试环境 JAVA JDK 1.7.0_13 (jdk-7u13-windows ...

随机推荐

  1. 查询数据过多页面反应慢引入缓存解决方案(Redis、H2)

      问题:原系统查询接口不支持分页也不可能加入分页支持,导致Ajax查询数据过多,返回数据达到2W多条记录时响应已经极慢,查询功能不要求数据实时性,页面反应速度极慢.体验不好:经排查是由于数据量过大导 ...

  2. WIN 下的超动态菜单(二)用法

    WIN 下的超动态菜单(一)简介 WIN 下的超动态菜单(二)用法 WIN 下的超动态菜单(三)代码 作者:黄山松,发表于博客园:http://www.cnblogs.com/tomview/     ...

  3. git pull

    今天在服务器上git pull是出现以下错误: error: Your local changes to the following files would be overwritten by mer ...

  4. Can't load AMD 64-bit .dll on a IA 32-bit platform

    主要谈谈在win8.1(64bit)下搭建环境的经历. 安装win8.1(64bit)后,配置java环境是费了我一番心思的,所以想记录下来,成为经验.64位系统下比较理想的配置应该是 64位jdk ...

  5. centos之开放80端口

    #/sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT  #/sbin/iptables -I INPUT -p tcp --dport 22 -j ...

  6. [转]OnKeyDown Numeric Validator CLIENT SIDE

    本文转自:http://forums.asp.net/t/1211724.aspx?OnKeyDown+Numeric+Validator+CLIENT+SIDE <!DOCTYPE html ...

  7. 123——Appium Girls活动

    有感于Ruby Girls和Python Girls,在15年就想组织一次移动测试的妹子活动,框架选择Appium, 从15年夏天开始准备,申请Google的会议室,招募教练,开放报名,审核报名,到正 ...

  8. XBOX ONE游戏开发之DEBUG配置(三)

    如何DEBUG 首先打开ADK命令提示窗口 输入命令 xbconnect {XBOX主机的IP} * XBOX主机的IP 在XBOX主机的开发者设置中可以看到,会有一个主机IP和一个工具IP 然后打开 ...

  9. document对象补充

    五.相关元素操作: var a = document.getElementById("id");                找到a: var b = a.nextSibling ...

  10. [No000035]操作系统Operating System之OS Interface操作系统接口

    接口(Interface) 仍然从常识开始… 日常生活中有很多接口:电源插座:汽车油门… 那什么是接口? 连接两个东西.信号转换.屏蔽细节… Interface: electrical circuit ...