The ItemsControlItemAutomationPeer leads memory leaks
Description
Hello, I encountered a memory leak issue with our components. During my research, I found that the key issue is caused bySystem.Windows.Automation.Peers.ItemsControlItemAutomationPeer.
It holds a reference to the user control (ViewA) via the field _itemsControlAutomationPeer.
How it works:
- We use a
ContentControland two views —ViewAandViewB. - On a button click, I change
ContentControl.Contentto a new instance of the view. - In this case, I expect that the previous instance of the view (
ViewA) should be collected, because it has been unloaded from the visual tree.
And this works until I start showing any popups.
At that moment, setting the new RootVisual causes the EnsureAutomation call.
This method forces the creation of the automation tree, and from that moment on, ItemsControlItemAutomationPeer holds a reference to ViewA.
Now, I’m looking for any help, solution, or workaround.
This is just a test sample, but we have a real-world scenario where our customer is suffering from this issue.
Reproduction Steps
- Run
MemoryLeakTestApp - Click
ShowPopupa couple of times - Take the first snapshot
- Click
ChangeView - Take the second snapshot
- Compare them and find the
ViewA
Expected behavior
The ViewA should be collected by the GC
Actual behavior
The ViewA remains in memory
Regression?
YES.
Under NET 6, it can't be reproduced, but there is another memory leak here (it is caused by AutomationPeer. _children.
I also tried to reproduce it under Framework 4.8, but it works properly without leaks
Known Workarounds
No response
Impact
No response
Configuration
WPF NET 9. This issue can be reproduced under NET 8 and higher.
Other information
No response
Source: dotnet/wpf