<?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/"
	>

<channel>
	<title>Neural Network Design blog &#187; C#</title>
	<atom:link href="http://janbogaerts.name/index.php/tag/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://janbogaerts.name</link>
	<description>My take on neural networks, AI and more</description>
	<lastBuildDate>Thu, 15 Dec 2011 18:43:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>WPF: a fast TreeView</title>
		<link>http://janbogaerts.name/index.php/2010/09/09/wpf-a-fast-treeview/</link>
		<comments>http://janbogaerts.name/index.php/2010/09/09/wpf-a-fast-treeview/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 12:29:30 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[treeview]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://janbogaerts.name/index.php/2010/09/09/wpf-a-fast-treeview/</guid>
		<description><![CDATA[An introduction on creating proper UI virtualization in WPF. It describes a technique to create treeviews in WPF that are able to display any amount of data while maintaining scroll speed and using a minimum of memory.]]></description>
			<content:encoded><![CDATA[<p>Are you getting sick already of WPF’s inability to handle large amounts of data? Well, I am,… definitely. After some final trials with the thesaurus (displayed in a tree), I gave up and decided to write my own virtualizing Treeview. Why? Here’s why:</p>
<ul>
<li>Scroll &amp; load speed: Even with full virtualization turned on, scrolling crawls almost to a halt when you have 60 000+ root items and a few of them are expanded some levels down the tree. The same for loading large lists.</li>
<li>Memory usage: probably related with the previous item, in short: kaboem!!!</li>
<li>BringIntoView: Here’s the killer, when virtualization is turned on, and the UI TreeViewIem hasn’t been rendered yet, you can’t bring it into view. Translated: you can’t do a search and show the found items in large trees, only in small trees (go figure).</li>
</ul>
<p>Note about my test data:  The thesaurus demo contains about 100 000 words (syn-sets actually), almost all of which have multiple relationships, so  in total, there are +500 000 nodes in the tree.</p>
<p>Ok,… and how do you fix this? Well here’s how I did it:</p>
<h4>Container rendering</h4>
<p>Virtualization means that you only render the UI elements that are currently visible, and not the whole tree (or a large part like microsoft does). This means that, for each UI object that got rendered, you somehow need to keep track of the data position in the tree. I do this by using 2 cursors: one for the first and another for the last visible element. This cursor is nothing more than a list of indexes into the tree.</p>
<p>All items in between those 2 cursors are flattened out (by rendering UI elements for them). The nr of indexes (or nr of parents) for each item, is used as the level for the UI element. This determines the amount of indentation to the right that is applied to the UI element.</p>
<p>When the user scrolls down, the bottom cursor is updated (advanced by the amount that the user scrolled). This is a basic tree walking algorithm. From this bottom index, we render objects while going up the tree until the panel is full (again, the same tree walking algorithm). The index path of the new top item becomes the new top cursor. The same technique is used to scroll up, but instead, you start from the top cursor and fill downwards.</p>
<p><em>Remark: Watch out while calculating the scroll difference: The scrollbar value is usually a double while we only consume integer values, so there might be some left over in the scroll difference which has to be consumed the next time you calculate the dif.</em></p>
<p>Of course, this technique only works if the TreeView has some knowledge of the data structure, how else can it find the children of the root items and see if they are expanded or not? This requires an interface. Here’s how mine looks like:</p>
<pre class="code"><span style="color: blue;">   public interface </span><span style="color: #2b91af;">ITreeViewItem
   </span>{<span style="color: gray;">
      </span><span style="color: blue;">bool </span>IsExpanded { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }<span style="color: gray;">
      </span><span style="color: blue;">bool </span>IsSelected { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }<span style="color: gray;">
      </span><span style="color: blue;">bool </span>HasChildren { <span style="color: blue;">get</span>; }<span style="color: gray;">
      </span><span style="color: #2b91af;">IList </span>TreeItems { <span style="color: blue;">get</span>; }<span style="color: gray;">
      </span><span style="color: #2b91af;">ITreeViewPanelItem </span>ParentTreeItem { <span style="color: blue;">get</span>; }
<span style="color: gray;">      </span><span style="color: blue;">bool </span>NeedsBringIntoView { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; }
   }</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Each tree node should implement this interface so that the TreeView can properly traverse the tree. A few properties are mostly for the visual parts, like ‘IsSelected’ or ’HasChildren’ (to display the toggle button). The last property is perhaps a bit of an odd one: ‘NeedsBringIntoView’. It’s a quick method to let the Tree know that an element needs to be brought into the viewable area. You could also use a function on the TreeView (like microsoft does), but then you are forced to go find the UI element from your search code to bring the item into view, which I wanted to avoid.</p>
<p>Using this technique, you do create and destroy a lot of containers since each time the user scrolls, the entire visible area is re-rendered. To minimize the impact of this on the garbage collector, it’s probably best to use some recycling scheme. This doesn’t have to be fancy: a simple queue to put the items in when clearing the list which can be consumed again when rendering the containers. I chose a queue since it gives best chances to reassign the same container to the same data object when possible, which minimizes the impact of re-rendering on the binding system.</p>
<h4>Events</h4>
<p>The second important thing for virtualized TreeViews, is the event system. You can not simply go and hook up event handlers to every data element. This would blow up the memory. Also, you’d have to write a lot of code to keep track of those events as data objects are being created and destroyed (trees of such a size can only work if you combine UI virtualization with data virtualization, but that’s an entire subject all together). On the other hand, events are VERY important to get UI virtualization working for keeping track of the maximum scroll count, tree nodes that get expanded/collapsed, objects that need to be brought into view, and UI elements that need to be updated.</p>
<p>Are you seeing the bubbles already? Yep: use bubbling events, like WPF does. The only problem: that doesn’t exist for regular objects, it’s only available in the WPF world. You could inherit all your objects from <em>DependencyObject</em>, but with 200 0000 objects in memory, that somehow becomes bloated. Better to roll out your own sleek, mean and fast event mechanism, which isn’t hard at all to do. Here’s a little sample code to bubble events up a tree:</p>
<pre class="code"><span style="color: blue;">public static void </span>OnPropertyChanged(<span style="color: #2b91af;">IOnBubblingChanged </span>sender, <span style="color: #2b91af;">BubblingPropertyChangedEventArgs </span>e)
{
   <span style="color: blue;">while </span>(sender != <span style="color: blue;">null</span>)                                  <span style="color: green;">//use a while loop to avoid recursive calls.
   </span>{
      sender.OnBubblingPropertyChanged(e);
      <span style="color: #2b91af;">IOwnedObject </span>iOwned = sender <span style="color: blue;">as </span><span style="color: #2b91af;">IOwnedObject</span>;
      <span style="color: blue;">if </span>(iOwned != <span style="color: blue;">null</span>)
         sender = iOwned.Owner <span style="color: blue;">as </span><span style="color: #2b91af;">IOnBubblingChanged</span>;
      <span style="color: blue;">else
         </span>sender = <span style="color: blue;">null</span>;                                    <span style="color: green;">//need to make the loop stop
   </span>}
}</pre>
<p>This function is called whenever a property on a tree item is changed. As you can see, a lot of interfaces are at work here. <em>IOnBubblingChanged</em> defines a function that can be called which will raise the event. IOwnedObject is one of my core interfaces for all objects that can be ‘owned’ by another object. This maps to the ‘<em>ParentTreeItem</em>’ property of the first <em>ITreeViewItem</em> interface.</p>
<p>A similar thing needs to be done for the <em>CollectionChanged</em> events. A remark on the ‘reset collection’ event: make certain that you can pass along the list of items that got cleared, otherwise the TreeView will have a hard time figuring out exactly how much the count needs to be decreased (were any of the removed items expanded?). The default WPF <em>NotifyCollectionChanged</em> event doesn’t do that, so you can’t simply use it’s event arguments.</p>
<p>With this type of bubbling event system, it’s probably best to work with some kind of ‘root’ object that defines the events for the property and collection changes in the entire tree. Again a nice job for an interface, I suppose. This root interface can be used as the <em>ItemsSource</em> for the treeview instead of a list, like WPF does. This way, you can have lots of root objects without overtaxing the .net event management system.</p>
<p>Using this technique, you can make Treeviews that aren’t only fast to load and scroll, but also use very little memory. I am silently hoping that microsoft will eventually pick up on this and begin implementing proper UI virtualization in the coming versions of WPF (thus relieving me from the burden). In the mean time, I guess we are left to roll out our own stuff.</p>
 <img src="http://janbogaerts.name/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=449" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://janbogaerts.name/index.php/2010/09/09/wpf-a-fast-treeview/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Deadlocks, again</title>
		<link>http://janbogaerts.name/index.php/2010/05/31/deadlocks-again/</link>
		<comments>http://janbogaerts.name/index.php/2010/05/31/deadlocks-again/#comments</comments>
		<pubDate>Mon, 31 May 2010 13:11:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[deadlocks]]></category>

		<guid isPermaLink="false">http://janbogaerts.name/index.php/2010/05/31/deadlocks-again/</guid>
		<description><![CDATA[I just spent the last 3 days chasing down 3 deadlocks that were teaming up against me. Man, I hate deadlocks. They were definitely the biggest obstacles so far in the development process. Simply because their origins are so hard to locate. And that, even though they are always caused by the same type of [...]]]></description>
			<content:encoded><![CDATA[<p>I just spent the last 3 days chasing down 3 deadlocks that were teaming up against me. Man, I hate deadlocks. They were definitely the biggest obstacles so far in the development process. Simply because their origins are so hard to locate. And that, even though they are always caused by the same type of situation: 2 threads intertwining with their locking scheme.</p>
<p>Put into sequence:</p>
<ol>
<li>Thread 1 locks x and continues execution (no waiting) </li>
<li>Thread 2 locks y and continues execution (no waiting) </li>
<li>Thread 1 requests y and waits </li>
<li>Thread 2 requests x and waits,… oeps </li>
</ol>
<p>The most often way to locate this situation is by examining the execution stack of the CPU. But what if you do out of sync locking: the request in function 1 and the release in function 2, without any relationship between the 2 functions. As an example, take the network-core’s lock expression, which is new. This locks the items when the statement is called, but releases them only after all the child statements were called. The interpreter obviously can’t do this in the same function call. </p>
<p> So how do you trace this type of bug? Well, slowly, painfully and with lots of debug code to generate application dumps. here’s the smallest dump that I generated for the core (usually it was several 100 lines longer):</p>
<p> <code>Links in    <br />ID: 7461 ReadCount: 2&#160; WriteCount: 0, Waiting: 0     <br />Links out     <br />ID: 7461 ReadCount: 2&#160; WriteCount: 0, Waiting: 0     <br />Values     <br />ID: 7461 ReadCount: 2&#160; WriteCount: 0, Waiting: 0     <br />Processors     <br />Parents     <br />ID: 7461 ReadCount: 0&#160; WriteCount: 0, Waiting: 2     <br />Children     <br />ID: 7432 ReadCount: 0&#160; WriteCount: 1, Waiting: 0     <br />ID: 7461 ReadCount: 2&#160; WriteCount: 0, Waiting: 0     <br />ID: 7288 ReadCount: 0&#160; WriteCount: 1, Waiting: 0     <br />LockExpressionCounter: 2     <br />Single lock count: 0</code>
<p>Basically, it allows me to check all the locks that are still active (in order of age) when the deadlock occurred. From then it’s simply a matter of figuring out who has the oldest lock and why it wasn’t released. To do this, it’s best to keep track somehow of the threads that do the locking and make certain that they are named, so you can find them again in the execution stack of the debugger.</p>
 <img src="http://janbogaerts.name/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=282" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://janbogaerts.name/index.php/2010/05/31/deadlocks-again/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WPF is getting under my skin</title>
		<link>http://janbogaerts.name/index.php/2010/02/24/wpf-is-getting-under-my-skin/</link>
		<comments>http://janbogaerts.name/index.php/2010/02/24/wpf-is-getting-under-my-skin/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 12:58:37 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[N²D]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://janbogaerts.name/index.php/2010/02/24/wpf-is-getting-under-my-skin/</guid>
		<description><![CDATA[I have been fighting the WPF model all the way during the development of NND. And it is wearing me down. Latest problem: the updated selection box for frame element filters doesn’t want to get focus, making it impossible to use the keyboard. I guess the new release will have to wait until I can [...]]]></description>
			<content:encoded><![CDATA[<p>I have been fighting the WPF model all the way during the development of NND. And it is wearing me down. Latest problem: the updated selection box for frame element filters doesn’t want to get focus, making it impossible to use the keyboard. I guess the new release will have to wait until I can get this fixed. Bummer.</p>
<p><a href="http://janbogaerts.name/wp-content/uploads/2010/02/image1.png"><img style="margin: 0px; display: inline; border-width: 0px;" title="image" src="http://janbogaerts.name/wp-content/uploads/2010/02/image_thumb1.png" alt="image" width="758" height="728" border="0" /></a></p>
 <img src="http://janbogaerts.name/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=191" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://janbogaerts.name/index.php/2010/02/24/wpf-is-getting-under-my-skin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

