Wednesday, December 28, 2011

WPF Memory Leak (DataTemple)


In WPF programming, there is a well-known memory leak which occurs when you use a DataTemplate to display tabs in Tabcontrol.  

If in a tab control you are creating tabs dynamically and also generating contents of those tabs using datatemplate binding as show below
    <DataTemplate DataType="{x:Type ViewModels:SomeViewModel}" >
                <views:SomeView  />
    </DataTemplate>

Then, you are injecting a potential memory leak in your application. Because whenever your tab is highlighted WPF runtime creates a new instance if “SomeView” class and uses it.
As of now only workaround for this problem is to use a ViewFactory which will supply your views. This ViewFactory will have a static object which will create only one instance of “SomeView” class and use it through application lifetime.
So, your changed code would look like
    <DataTemplate DataType="{x:Type ViewModels:SomeViewModel}" >
        <ContentPresenter Content="{x:Static local:ViewsFactory.SomeViewInstance}" />
    </DataTemplate>

And implementation of your ViewFactory class would be something like
 public static class ViewsFactory
    {
        #region SomeViewInstance

        private static SomeView _SomeViewInstance = null;

        /// <summary>
        /// Gets or sets the  SomeViewInstance  property. 
        /// </summary>
        public static SomeView SomeViewInstance
        {
            get
            {
                if (_SomeViewInstance == null)
                {
                    _SomeViewInstance = new SomeView();
                }

                return _SomeViewInstance;
            }
        }

        #endregion
    }

Hope it helps!!!

No comments:

Post a Comment