当我在应用程序中发现内存泄漏时,我使用分析工具来检测非托管内存是否在不断增加;然后我使用二进制搜索方法来定位可能导致内存问题的API。这意味着如果在函数上下文中调用API,则存在内存问题;如果API在代码中被注释,则内存问题不会显示出来。附上代码供您参考:
class Program
{
private static void Main(string[] args)
{
Accelerometer acc = Accelerometer.GetDefault();
if (acc == null)
{
Console.WriteLine("NULL instance received");
return;
}
Console.WriteLine("acc created taking sample");
var reading = acc.GetCurrentReading();
if (reading == null)
{
}
else
{
}
acc.ReadingChanged += acc_ReadingChanged; ;
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
private static void acc_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
{
var reading = args.Reading;
// below code is the place where memory leak happens
// actually nothing is done here
// start
foreach (var item in reading.Properties)
{
}
// end
double[] Data = new[] { reading.AccelerationX, reading.AccelerationY, reading.AccelerationZ };
Console.WriteLine(Data[0].ToString() + Data[1].ToString()+Data[2].ToString());
}
}
代码是否有任何问题,例如使用foreach或KeyPairValue?API链接:https://docs.microsoft.com/en-us/uwp/api/windows.devices.sensors.accelerometerreading