Visual tree element detaching and reattaching operations can lead to memory leaks
See original GitHub issueScenario
I need to dynamically modify ControlTheme or Style and apply the changes to the existing interface immediately.
In 11.0.0, I can only apply real-time changes to ControlTheme by using reflection to call the StyledElement.OnControlThemeChanged
and StyledElement.OnTemplatedParentControlThemeChanged
methods on all elements in the visual tree. Then, I call StyledElement.InvalidStyles()
to apply Style changes.
I know this is not a robust and good solution. But currently, I have no other way. Then, I encountered a memory leak issue.
Describe the bug
So I modified the approach by breaking down the content of the Window from the visual tree and then putting it back to update the ControlTheme and Style of all elements under this subtree. Unfortunately, this operation also resulted in a memory leak.
I repeated this process 100 times and monitored the memory changes, and found that there were many objects in Generation 2 that increased during this process, even though I manually executed GC.Collect(), it didn’t have any effect.
The Code To Reproduce
// Note that the window should have something as it's content.
public class MainWindow : Window
{
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
var content = this.Content;
Task.Delay(3000).ContinueWith(t =>
{
for (var i = 0; i < 100; i++)
{
Dispatcher.UIThread.Post(() =>
{
this.Content = null;
this.Content = content;
});
Thread.Sleep(200);
}
});
}
}
Expected behavior
Even without considering the rare and unconventional scenarios described above, frequent detaching and reattaching operations from the visual tree should not lead to the continuous generation of unreleased memory objects.
Screenshots
Desktop
- OS: Windows 11
- Version 11.0.0.
Issue Analytics
- State:
- Created a month ago
- Comments:7 (3 by maintainers)
Top GitHub Comments
Ok, I will see that later. Thank you 👍 @timunie
No I guess I stopped debugger too early. Sorry. After having a deeper look it may be related to: https://github.com/AvaloniaUI/Avalonia/issues/12416
There’s a PR which should address this. You can try it here: https://github.com/AvaloniaUI/Avalonia/pull/12418#issuecomment-1662069675