WPF ElementHost 内存泄露问题
无意中发现,WPF ElementHost 控件如果未正确释放,会存在内存泄露问题。解决方法如下:
xaml代码:
<Grid x:Name="grid">
<WindowsFormsHost x:Name="host">
<ElementHost x:Name="elementHost">
<local:MultiPlayerController x:Name="multiPlayer"></local:MultiPlayerController>
</ElementHost>
</WindowsFormsHost>
</Grid>
后台资源释放代码:
public void Dispose()
{
multiPlayer.StopAll();
if (elementHost != null)
{
FrameworkElement frameworkElement = elementHost.Child as FrameworkElement;
if (frameworkElement != null)
{
// Memory leak workaround: elementHost.Child.SizeChanged -= elementHost.childFrameworkElement_SizeChanged;
SizeChangedEventHandler handler = (SizeChangedEventHandler)Delegate.CreateDelegate(typeof(SizeChangedEventHandler), elementHost, "childFrameworkElement_SizeChanged");
frameworkElement.SizeChanged -= handler;
}
elementHost.Child = null;
elementHost.Dispose();
elementHost = null;
}
if (host != null)
{
host.Child = null;
host.Dispose();
host = null;
}
grid.Children.Clear();
}
关键代码:
SizeChangedEventHandler handler = (SizeChangedEventHandler)Delegate.CreateDelegate(typeof(SizeChangedEventHandler), elementHost, "childFrameworkElement_SizeChanged");
frameworkElement.SizeChanged -= handler;
另外 grid.Children.Clear() 也不能省。
参考资料:https://stackoverflow.com/questions/24823103/how-to-clear-memoryleak-from-elementhost-control