Actual Behavior:
- Memory usage continuously increases over time
- Memory is not being released even with proper disposal patterns implemented
Code Implementation:
using System.Collections.ObjectModel;
namespace MauiListView
{
public class Message
{
public string? Content { get; set; }
public DateTime Timestamp { get; set; }
}
public partial class MainPage : ContentPage, IDisposable
{
private const int MAX_MESSAGES = 10;
private readonly ObservableCollection<Message> messages;
private IDispatcherTimer? timer;
private bool isDisposed;
public MainPage()
{
InitializeComponent();
messages = new ObservableCollection<Message>();
MessageListView.ItemsSource = messages;
}
private void StartMessageGeneration()
{
// 이전 타이머가 있다면 정리
StopAndDisposeTimer();
timer = Application.Current?.Dispatcher.CreateTimer();
if (timer != null)
{
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += Timer_Tick;
timer.Start();
}
}
private void StopAndDisposeTimer()
{
if (timer != null)
{
timer.Stop();
timer.Tick -= Timer_Tick; // 이벤트 핸들러 해제
timer = null;
}
}
private void Timer_Tick(object? sender, EventArgs e)
{
if (messages == null) return;
var message = new Message
{
Content = $"새로운 메시지 {DateTime.Now}",
Timestamp = DateTime.Now
};
MainThread.BeginInvokeOnMainThread(() =>
{
messages.Insert(0, message);
while (messages.Count > MAX_MESSAGES)
{
messages.RemoveAt(messages.Count - 1);
}
});
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!isDisposed)
{
if (disposing)
{
StopAndDisposeTimer();
messages.Clear();
MessageListView.ItemsSource = null;
}
isDisposed = true;
}
}
protected override void OnAppearing()
{
base.OnAppearing();
StartMessageGeneration();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
StopAndDisposeTimer();
}
~MainPage()
{
Dispose(false);
}
}
}
Environment:
- .NET MAUI version: 8.0
- Platform tested: Windows
What I've tried:
- Implemented IDisposable pattern
- Clearing ItemsSource on disposal
- Properly unsubscribing from events
- Limiting collection size with MAX_MESSAGES
- Using MainThread.BeginInvokeOnMainThread for UI updates
Expected Behavior:
- ListView should maintain stable memory usage
- Memory should be properly cleaned up when items are removed from the ObservableCollection
Dispose. Generally, you don't needDisposeunless you need to release unmanaged resources, or for some other special purposes.<ListView CachingStrategy="RecycleElement">