I'm seeing some serious memory leaks from a simple string formatting operation. I noticed this due my application UI getting slower over time. I decided to create a very simple solution to isolate and test this issue by itself. It would be great to get somebody else opinion. I'm placing the basics for a XF Android project you can run with the memory profiler to see the problem. Not sure why updating a view label will cause memory leaks. Even just creating a string in the thread and not assign it to the label causes memory leaks. What am I doing wrong here? Thanks!
using System;
using Xamarin.Forms;
namespace testMemoryLeaks
{
public class App : Application
{
public App()
{
MainPage = new RandomNumbers();
}
}
}
using System;
namespace testMemoryLeaks
{
public static class Data
{
public static double LastRandomNumber = 0.0;
public static void UpdateRandomNumber()
{
Random random = new Random();
var next = random.NextDouble();
LastRandomNumber = 0 + (next * 1000);
}
}
}
using System;
using System.Collections.Generic;
using Xamarin.Forms;
using System.Threading;
namespace testMemoryLeaks
{
public partial class RandomNumbers : ContentPage
{
public Label numberLabel;
private string someText = "";
private bool _dataThreadEnabled = true;
private bool _uiUpdateThreadEnabled = true;
public RandomNumbers()
{
numberLabel = new Label()
{
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.Center,
TextColor = Color.White,
Text = "Random Numbers",
FontSize = 24,
XAlign = TextAlignment.Center
};
StackLayout pageStack = new StackLayout
{
HorizontalOptions = LayoutOptions.CenterAndExpand,
VerticalOptions = LayoutOptions.CenterAndExpand,
Children =
{
numberLabel
}
};
Content = pageStack;
StartProcessingThreads();
}
public void StartProcessingThreads()
{
// Data processing:
ThreadPool.QueueUserWorkItem(state =>
{
// Updates here
while (_dataThreadEnabled)
{
Data.UpdateRandomNumber();
Thread.Sleep(20);
}
});
// UI updating
ThreadPool.QueueUserWorkItem(state =>
{
Thread.Sleep(3000);
// Start loop updating values
while (_uiUpdateThreadEnabled)
{
// Update screen's gauges values only
Device.BeginInvokeOnMainThread(() =>
{
// Update label. This line is what seems to cause the memory leaks ************
numberLabel.Text = string.Format("Numbers {0:0.00}", Data.LastRandomNumber);
});
}
Thread.Sleep(25);
});
}
}
}