Created a minimal reproducing application.
Reproducing conditions:
- Visual Studio 2017
- WPF application
- Launch the application under the debugger
- WPF window code (class with finalizer, very busy WPF main thread):
code:
using System.Windows;
namespace ReproduceFinalizerMemoryLeak
{
public partial class MainWindow : Window
{
public MainWindow()
{
do
{
Item item = new Item();
} while (true);
InitializeComponent();
}
}
public class Item
{
private byte[] _bytes;
public Item()
{
_bytes = new byte[10000];
}
~Item()
{
}
}
}
What comes up:
This application crashes with OutOfMemoryException. Item class finalizer is not called. Instances of Item class are not unloaded from memory and stays in f-reachable queue.
In my real WPF application, a memory leak occurs without debugging and under other conditions, but the manifestations are the same: finalizers are not called, memory leaks. See details and memory profiling screenshots here.
There are no problems with garbage collection if
- I run code above in console application
- or I run code above with class without finalizer (in my real WPF application or sample application)
It seems that under certain conditions WPF main thread blocks the thread in which finalizers are called.