Silverlight控制与xaml - 资源消耗

时间:2016-09-29 15:14:13

标签: c# xaml silverlight resources silverlight-5.0

我在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()

我的问题是:

  • 是否有可能在Silverlight中启用某种类型的缓存机制,以便在实例化某些UserControl时,Framework会识别出之前加载了xaml而没有做同样的事情再次仅在第一次加载xaml时?
  • 是否有其他一些机制或良好做法可以避免每次都加载相同的xaml?

我有提到的各种控件的基本示例。您可以在下面找到代码示例。 这只是一个基本的例子,没有任何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。

Memory allocation (Jetbrains dot trace)

类似的事情是我们比较两个控件的实例化时间。

Trace - calls number and execution time

0 个答案:

没有答案