Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Memory Leak in WPF (ListBox)?

$
0
0

Dear all,

 

I know, I know, another nutcase that can't code claiming a memory leak, right? Bear with me:

 

All this code does is, every 0.1 seconds, clear a ListBox (listBox1) and add a bunch of strings to it (DateTime.Now strings, to be precise). See below for (a very short) code block. Try for yourself if you wish.

 

Code Block

publicpartialclassWindow1 : Window

{

  privateDispatcherTimer timer;

 

  public Window1()

  {

     InitializeComponent();

     timer = newDispatcherTimer(TimeSpan.FromSeconds(0.1), DispatcherPriority.Normal, newEventHandler(UpdateLabels), this.Dispatcher);

     timer.Start();

  }

 

  privatevoid UpdateLabels(object Sender, EventArgs EA)

  {

    listBox1.Items.Clear();

    for(int i=0; i<100; i++)

    {

       listBox1.Items.Add(DateTime.Now.ToString());

    }

  }

}

 

The thing is: The memory grows quite a bit. I memory profiled this thing and it turns out that there are a bunch of WeakReference instances created that don't ever get collected. Ever. Not Generation 1. Not Generation 2. Never.

According to the memory profiler, they are somehow tied to Dependent[].

 

(Note that the leak does not happen if I just take a ListBox and pre-populate 100 items, then update those. Then no WeakReferences are being kept. So somehow, ListBox's Items.Clear() must be the culprit and not letting go of some of these.).

 

Why is that? Of course maybe I'm just a dweeb (more likely) and can't figure out what I'm doing wrong. In that case, perhaps someone could throw some light on the issue.

 

Many thanks in advance. Happy to post additional infos. I'd like to post a screenshot of the memory profile for the above application but this thing won't let me attach pictures.


Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>