我在Silverlight 5 app中面临内存消耗问题。
经过几天的测量,我发现主要内存消费者是自定义UserControls(使用xaml),并且这些控件从没有xaml的其他控件中脱颖而出(例如从System.Windows继承) .Controls.TextBox(System.Windows.Controls.Control))。
我很惊讶地发现,当Silverlight控件调用app.yaml
(构造函数)时,Framework每次都调用InitializeComponent();
以获取xaml。
那么,如果要动态创建500个控件(相同类型),Framework会调用System.Windows.Application.LoadComponent(Object, Uri)
500次?我预计只有在第一次实例化控件时才加载xaml,之后不再加载LoadComponent()
。
我的问题是:
我有提到的各种控件的基本示例。您可以在下面找到代码示例。 这只是一个基本的例子,没有任何Binding,DataContext对象,Dependency属性等等。
控件的
继承自System.Windows.Controls.TextBox的МyTextBox.cs
LoadComponent()
MyText.xaml
using System.Windows.Controls;
namespace TestControls.Controls
{
public class МyTextBox : TextBox
{
public МyTextBox()
{
Text = "MyTextBox";
}
}
}
MyText.xaml.cs
<UserControl x:Class="TestControls.Controls.MyText"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Name="Text"/>
</Grid>
</UserControl>
应用
MainPage.xaml中
using System.Windows.Controls;
namespace TestControls.Controls
{
public partial class MyText : UserControl
{
public MyText()
{
InitializeComponent();
Text.Text = "MyTextControl";
}
}
}
MainPage.xaml.cs中
<UserControl x:Class="TestControlsApplication.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<StackPanel Name="Panel"/>
</Grid>
</UserControl>
MyText控件(有xaml)分配5,1 MB(所有实例)和继承System.Windows.Controls.TextBox的MyTextBox分配了0.4 MB。
类似的事情是我们比较两个控件的实例化时间。