How to identify and fix memory leaks in WPF BeginInvoke ()?

I am working with Windows.Net C # WPF. The app displays video frames in addition to displaying some additional analytics in the canvas.

The app processes a frame rate of around 15 frames per second. Processing is carried out on a separate topic. The processing thread dispatches callbacks when the analysis completes and the display is refreshed.

I noticed some significant memory growth (leaks) when running the application over a period of time. After working for several hours, the application memory grows to 200 MB.

To try and track these leaks, I am using red-gate ANTs memory profiling. Based on the results obtained, it looks like my calls to dispeger.BeginInvoke () are the source of at least some leaks.

The .BeginInvoke () dispatcher is required as I am updating the UI from a different thread (other than the UI thread).

Here's some sample code from the app:

canvas.Dispatcher.BeginInvoke((Action)(() =>
   // Clear the previous points
   SolidColorBrush pointBrush = new SolidColorBrush(Colors.Cornsilk);
   foreach (var point in points)
      Ellipse ellipse = new Ellipse()
         Width = 4,
         Height = 4,
         Fill = pointBrush

      Canvas.SetLeft(ellipse, point.x * XScaleFactor);
      Canvas.SetTop(ellipse, point.y * YScaleFactor);

   SolidColorBrush boundingBrush = new SolidColorBrush(Colors.Bisque);
   Rectangle boundingBox = new Rectangle()
      Width = width,
      Height = height,
      Stroke = boundingBrush,
      StrokeThickness = 1,

   Canvas.SetLeft(boundingBox, xMin * mImageXScaleFactor);
   Canvas.SetTop(boundingBox, yMin * mImageYScaleFactor);


After running with Red-gate Memory Profiler, I see many instances of the Dispatcher () class that look like they are leaking about 64 bytes per instance. Keeping in mind that I am processing 15 frames per second, this adds up steadily. Is there something graphical going on inside the anonymous function block that prevents the overhead associated with each BeginInvoke () release?

How do I figure out what is going on here and how to fix this problem?

Thanks, JohnB


source to share

All Articles