<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Kiener&#039;s Blog &#187; Bug</title>
	<atom:link href="http://blog.thekieners.com/tag/bug/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.thekieners.com</link>
	<description>Blog of Beat Kiener, containing my experiences, thoughts, comments and questions</description>
	<lastBuildDate>Thu, 26 Jan 2012 02:01:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.thekieners.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Kiener&#039;s Blog &#187; Bug</title>
		<link>http://blog.thekieners.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.thekieners.com/osd.xml" title="Kiener&#039;s Blog" />
	<atom:link rel='hub' href='http://blog.thekieners.com/?pushpress=hub'/>
		<item>
		<title>Memory leak with focusable UIElement in Silverlight?</title>
		<link>http://blog.thekieners.com/2010/01/28/memory-leak-with-focusable-uielement-in-silverlight/</link>
		<comments>http://blog.thekieners.com/2010/01/28/memory-leak-with-focusable-uielement-in-silverlight/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 13:08:00 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Bug]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/01/28/memory-leak-with-focusable-uielement-in-silverlight/</guid>
		<description><![CDATA[Suppose we have a StackPanel with following controls inside. &#60;StackPanel x:Name=&#34;stackpanel&#34; Width=&#34;200&#34;&#62; &#60;TextBox /&#62; &#60;CheckBox /&#62; &#60;ComboBox /&#62; &#60;controls:DatePicker /&#62; &#60;Button /&#62; &#60;local:MyTextBox /&#62; &#60;/StackPanel&#62; &#160; All of them are focusable controls. MyTextBox is a subclass of TextBox as following: public class MyTextBox : TextBox { ~MyTextBox() { Debug.WriteLine(&#34;MyTextBox.Finalize&#34;); } } &#160; Now, if I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&amp;blog=7436128&amp;post=330&amp;subd=bkiener&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Suppose we have a StackPanel with following controls inside.</p>
<pre>        <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">StackPanel</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Name</span>=<span style="color:#0000ff;">&quot;stackpanel&quot;</span> <span style="color:#ff0000;">Width</span>=<span style="color:#0000ff;">&quot;200&quot;</span><span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">CheckBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">ComboBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">controls</span>:<span style="color:#800000;">DatePicker</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Button</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">MyTextBox</span> <span style="color:#0000ff;">/&gt;</span>
        <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">StackPanel</span><span style="color:#0000ff;">&gt;</span></pre>
<p>&#160;</p>
<p>All of them are focusable controls. MyTextBox is a subclass of TextBox as following:</p>
<pre>    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> MyTextBox : TextBox
    {
        ~MyTextBox()
        {
            Debug.WriteLine(&quot;<span style="color:#8b0000;">MyTextBox.Finalize</span>&quot;);
        }
    }</pre>
<p>&#160;</p>
<p>Now, if I remove the Children in the stackpanel&#8230;</p>
<pre><span style="color:#0000ff;">this</span>.stackpanel.Children.Clear();</pre>
<p>
  <br />&#8230;all Children gets garbage collected. Everything correct until here.</p>
<p>&#160;</p>
<p>Restart the application. Now set the focus to any element in the stackpanel and stepwise to all others too.<br />
  <br />If I now remove all children from the stackpanel none of them gets garbage collected.</p>
<pre><span style="color:#0000ff;">this</span>.stackpanel.Children.Clear();</pre>
<p>
  <br />Unfortunately, this problem has several negative side effects. We are using the MVVM pattern and when we databind the controls to a ViewModel then the ViewModel is also part of the memory leak, because the binding contains a reference to the ViewModel.</p>
<p>It also doesn&#8217;t help to remove the whole page. I&#8217;ve tested the code within a navigation application with the same result.</p>
<p>&#160;</p>
<h2>Demo Project</h2>
<p>Donwload the <a href="http://files.thekieners.com/blogcontent/PossibleMemoryLeak.zip" target="_blank"><strong>demo project here</strong></a>.</p>
<p>Please note: perhaps you have to run the GC n-times to collect all object, but at the end all elements which had the focus at any time will never be collected neither when you run the GC 1000 times or neither when you release the whole user control.</p>
<p>&#160;</p>
<h2>XAML snapshot</h2>
<pre>    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Grid</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Name</span>=<span style="color:#0000ff;">&quot;LayoutRoot&quot;</span> <span style="color:#ff0000;">Background</span>=<span style="color:#0000ff;">&quot;White&quot;</span><span style="color:#0000ff;">&gt;</span>

        <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">StackPanel</span> <span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Button</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Name</span>=<span style="color:#0000ff;">&quot;btnRemove&quot;</span> <span style="color:#ff0000;">Content</span>=<span style="color:#0000ff;">&quot;Remove all&quot;</span> <span style="color:#ff0000;">Click</span>=<span style="color:#0000ff;">&quot;btnRemove_Click&quot;</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Button</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Name</span>=<span style="color:#0000ff;">&quot;btnCollect&quot;</span> <span style="color:#ff0000;">Content</span>=<span style="color:#0000ff;">&quot;Run Garbage Collector&quot;</span> <span style="color:#ff0000;">Click</span>=<span style="color:#0000ff;">&quot;btnCollect_Click&quot;</span>  <span style="color:#0000ff;">/&gt;</span>
        <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">StackPanel</span><span style="color:#0000ff;">&gt;</span>

        <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">StackPanel</span> <span style="color:#ff0000;">x</span>:<span style="color:#ff0000;">Name</span>=<span style="color:#0000ff;">&quot;stackpanel&quot;</span> <span style="color:#ff0000;">Width</span>=<span style="color:#0000ff;">&quot;200&quot;</span><span style="color:#0000ff;">&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">TextBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">CheckBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">ComboBox</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">controls</span>:<span style="color:#800000;">DatePicker</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Button</span> <span style="color:#0000ff;">/&gt;</span>
            <span style="color:#0000ff;">&lt;</span><span style="color:#c71585;">local</span>:<span style="color:#800000;">MyTextBox</span> <span style="color:#0000ff;">/&gt;</span>
        <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">StackPanel</span><span style="color:#0000ff;">&gt;</span>

    <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Grid</span><span style="color:#0000ff;">&gt;</span></pre>
<p>&#160;</p>
<h2>C# snapshot</h2>
<pre>    <span style="color:#0000ff;">public</span> partial <span style="color:#0000ff;">class</span> MainPage : UserControl
    {
        <span style="color:#0000ff;">private</span> List&lt;WeakReference&gt; weakRefs = <span style="color:#0000ff;">new</span> List&lt;WeakReference&gt;();

        <span style="color:#0000ff;">public</span> MainPage()
        {
            InitializeComponent();

            <span style="color:#008000;">// collect all children to get a weakreference to it</span>
            <span style="color:#0000ff;">foreach</span> (UIElement element <span style="color:#0000ff;">in</span> <span style="color:#0000ff;">this</span>.stackpanel.Children)
                weakRefs.Add(<span style="color:#0000ff;">new</span> WeakReference(element));

            <span style="color:#008000;">// add the view model to the list too</span>
            weakRefs.Add(<span style="color:#0000ff;">new</span> WeakReference(<span style="color:#0000ff;">this</span>.DataContext));
        }

        <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">void</span> btnRemove_Click(<span style="color:#0000ff;">object</span> sender, RoutedEventArgs e)
        {
            <span style="color:#008000;">// removing the DataContext forces a rebind of all databound controls. </span>
            <span style="color:#008000;">// This releases the binding-reference from the control to the ViewModel.</span>
            <span style="color:#0000ff;">this</span>.DataContext = <span style="color:#0000ff;">null</span>;

            <span style="color:#008000;">// important: first remove the datacontext and then clear the children </span>
            <span style="color:#008000;">//            otherwise the ViewModel is part of the memory leak.</span>
            <span style="color:#0000ff;">this</span>.stackpanel.Children.Clear();
        }

        <span style="color:#0000ff;">private</span> <span style="color:#0000ff;">void</span> btnCollect_Click(<span style="color:#0000ff;">object</span> sender, RoutedEventArgs e)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();

            <span style="color:#008000;">// count how many reference are not collected</span>
            var objectsAlive = (from wr <span style="color:#0000ff;">in</span> weakRefs
                                where wr.IsAlive
                                select wr.Target).ToList();

            Debug.WriteLine(&quot;<span style="color:#8b0000;">Total instances not collected: </span>&quot; + objectsAlive.Count);
            objectsAlive.ForEach(obj =&gt; Debug.WriteLine(&quot;<span style="color:#8b0000;">     </span>&quot; + obj.GetType().Name));
        }

    }

    <span style="color:#008000;">// class to output the finalizing</span>
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> MyTextBox : TextBox
    {
        ~MyTextBox()
        {
            Debug.WriteLine(&quot;<span style="color:#8b0000;">MyTextBox.Finalize</span>&quot;);
        }
    }</pre>
<p>&#160;</p>
<h2>Feedback</h2>
<p>I’ve posted this problem on the silverlight.net forum as a possible bug. <a href="http://forums.silverlight.net/forums/p/158724/355572.aspx" target="_blank"><strong>Check it out here</strong></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bkiener.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bkiener.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/330/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&amp;blog=7436128&amp;post=330&amp;subd=bkiener&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/01/28/memory-leak-with-focusable-uielement-in-silverlight/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>
	</item>
	</channel>
</rss>
