<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Reed Copsey, Jr.</title>
	
	<link>http://reedcopsey.com</link>
	<description>Thoughts on C#, WPF, .NET, and programming for Scientific Visualization</description>
	<lastBuildDate>Sat, 06 Mar 2010 01:09:47 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/ReedCopsey" /><feedburner:info uri="reedcopsey" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Parallelism in .NET – Part 12, More on Task Decomposition</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/ZaJvW0Ctlbg/</link>
		<comments>http://reedcopsey.com/2010/03/05/parallelism-in-net-part-12-more-on-task-decomposition/#comments</comments>
		<pubDate>Sat, 06 Mar 2010 01:09:47 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/03/05/parallelism-in-net-part-12-more-on-task-decomposition/</guid>
		<description><![CDATA[Many tasks can be decomposed using a Data Decomposition approach, but often, this is not appropriate.&#160; Frequently, decomposing the problem into distinctive tasks that must be performed is a more natural abstraction.
However, as I mentioned in Part 1, Task Decomposition tends to be a bit more difficult than data decomposition, and can require a bit [...]]]></description>
			<content:encoded><![CDATA[<p>Many tasks can be <a href="http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/" target="_blank">decomposed</a> using a Data Decomposition approach, but often, this is not appropriate.&#160; Frequently, decomposing the problem into distinctive tasks that must be performed is a more natural abstraction.</p>
<p>However, as I mentioned in <a href="http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/" target="_blank">Part 1</a>, Task Decomposition tends to be a bit more difficult than data decomposition, and can require a bit more effort.&#160; Before we being parallelizing our algorithm based on the tasks being performed, we need to decompose our problem, and take special care of certain considerations such as ordering and grouping of tasks.</p>
<p> <span id="more-216"></span>
<p>Up to this point in this series, I’ve focused on parallelization techniques which are most appropriate when a problem space can be decomposed by data.&#160; Using <a href="http://msdn.microsoft.com/en-us/library/dd460688(v=VS.100).aspx" target="_blank">PLINQ</a> and the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel(v=VS.100).aspx" target="_blank">Parallel class</a>, I’ve shown how problem spaces where there is a collection of data, and each element needs to be processed, can potentially be parallelized.</p>
<p>However, there are many other routines where this is not appropriate.&#160; Often, instead of working on a collection of data, there is a single piece of data which must be processed using an algorithm or series of algorithms.&#160; Here, there is no collection of data, but there may still be opportunities for parallelism.</p>
<p>As I mentioned before, in cases like this, the approach is to look at your overall routine, and <a href="http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/" target="_blank">decompose your problem space based on tasks</a>.&#160; The idea here is to look for discrete “tasks,” individual pieces of work which can be conceptually thought of as a single operation.</p>
<p>Let’s revisit the example I used in <a href="http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/" target="_blank">Part 1</a>, an application startup path.&#160; Say we want our program, at startup, to do a bunch of individual actions, or “tasks”.&#160; The following is our list of duties we must perform right at startup:</p>
<ul>
<li>Display a splash screen </li>
<li>Request a license from our license manager </li>
<li>Check for an update to the software from our web server </li>
<li>If an update is available, download it </li>
<li>Setup our menu structure based on our current license </li>
<li>Open and display our main, welcome Window </li>
<li>Hide the splash screen </li>
</ul>
<p><strong>The first step in Task Decomposition is breaking up the problem space into discrete tasks.</strong></p>
<p>This, naturally, can be abstracted as seven discrete tasks.&#160; In the serial version of our program, if we were to diagram this, the general process would appear as:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/03/serial_w.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="serial_w" border="0" alt="serial_w" src="http://reedcopsey.com/blog/wp-content/uploads/2010/03/serial_w_thumb.png" width="176" height="535" /></a>These tasks, obviously, provide some opportunities for parallelism.&#160; Before we can parallelize this routine, we need to analyze these tasks, and find any dependencies between tasks.&#160; In this case, our dependencies include:</p>
<ul>
<li>The splash screen must be displayed first, and as quickly as possible.</li>
<li>We can’t download an update before we see whether one exists.</li>
<li>Our menu structure depends on our license, so we must check for the license before setting up the menus.</li>
<li>Since our welcome screen will notify the user of an update, we can’t show it until we’ve downloaded the update.</li>
<li>Since our welcome screen includes menus that are customized based off the licensing, we can’t display it until we’ve received a license.</li>
<li>We can’t hide the splash until our welcome screen is displayed.</li>
</ul>
<p>By listing our dependencies, we start to see the natural ordering that must occur for the tasks to be processed correctly.</p>
<p><strong>The second step in Task Decomposition is determining the dependencies between tasks, and ordering tasks based on their dependencies.</strong></p>
<p>Looking at these tasks, and looking at all the dependencies, we quickly see that even a simple decomposition such as this one can get quite complicated.&#160; In order to simplify the problem of defining the dependencies, it’s often a useful practice to group our tasks into larger, discrete tasks.&#160; The goal when grouping tasks is that you want to make each task “group” have as few dependencies as possible to other tasks or groups, and then work out the dependencies within that group.&#160; Typically, this works best when any external dependency is based on the “last” task within the group when it’s ordered, although that is not a firm requirement.&#160; This process is often called <strong>Grouping Tasks</strong>.&#160; In our case, we can easily group together tasks, effectively turning this into four discrete task groups:</p>
<p><strong>1. Show our splash screen – </strong></p>
<p>This needs to be left as its own task.&#160; First, multiple things depend on this task, mainly because we want this to start before any other action, and start as quickly as possible.</p>
<p><strong>2. Check for Update and Download the Update if it Exists -</strong></p>
<p>These two tasks logically group together.&#160; We know we only download an update if the update exists, so that naturally follows.&#160; This task has one dependency as an input, and other tasks only rely on the final task within this group.</p>
<p><strong>3. Request a License, and then Setup the Menus &#8211; </strong></p>
<p>Here, we can group these two tasks together.&#160; Although we mentioned that our welcome screen depends on the license returned, it also depends on setting up the menu, which is the final task here.&#160; Setting up our menus cannot happen until after our license is requested.&#160; By grouping these together, we further reduce our problem space.</p>
<p><strong>4. Display welcome and hide splash -</strong></p>
<p>Finally, we can display our welcome window and hide our splash screen.&#160; This task group depends on all three previous task groups – it cannot happen until all three of the previous groups have completed.</p>
<p>By grouping the tasks together, we reduce our problem space, and can naturally see a pattern for how this process can be parallelized.&#160; The diagram below shows one approach:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/03/parallel_w.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="parallel_w" border="0" alt="parallel_w" src="http://reedcopsey.com/blog/wp-content/uploads/2010/03/parallel_w_thumb.png" width="522" height="518" /></a> </p>
<p>The orange boxes show each task group, with each task represented within.&#160; We can, now, effectively take these tasks, and run a large portion of this process in parallel, including the portions which may be the most time consuming.&#160; We’ve now created two parallel paths which our process execution can follow, hopefully speeding up the application startup time dramatically.</p>
<p>The main point to remember here is that, when decomposing your problem space by tasks, you need to:</p>
<ul>
<li>Define each discrete action as an individual Task</li>
<li>Discover dependencies between your tasks</li>
<li>Group tasks based on their dependencies</li>
<li>Order the tasks and groups of tasks</li>
</ul>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/ZaJvW0Ctlbg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/03/05/parallelism-in-net-part-12-more-on-task-decomposition/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/03/05/parallelism-in-net-part-12-more-on-task-decomposition/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 11, Divide and Conquer via Parallel.Invoke</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/RMA0PRiyyAE/</link>
		<comments>http://reedcopsey.com/2010/02/26/parallelism-in-net-part-11-divide-and-conquer-via-parallel-invoke/#comments</comments>
		<pubDate>Sat, 27 Feb 2010 00:00:31 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/02/26/parallelism-in-net-part-11-divide-and-conquer-via-parallel-invoke/</guid>
		<description><![CDATA[Many algorithms are easily written to work via recursion.&#160; For example, most data-oriented tasks where a tree of data must be processed are much more easily handled by starting at the root, and recursively “walking” the tree.&#160; Some algorithms work this way on flat data structures, such as arrays, as well.&#160; This is a form [...]]]></description>
			<content:encoded><![CDATA[<p>Many algorithms are easily written to work via <a href="http://en.wikipedia.org/wiki/Recursion" target="_blank">recursion</a>.&#160; For example, most data-oriented tasks where a tree of data must be processed are much more easily handled by starting at the root, and recursively “walking” the tree.&#160; Some algorithms work this way on flat data structures, such as arrays, as well.&#160; This is a form of <a href="http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm" target="_blank">divide and conquer</a>: an <a href="http://en.wikipedia.org/wiki/Algorithm_design" target="_blank">algorithm design</a> which is based around breaking up a set of work recursively, “dividing” the total work in each recursive step, and “conquering” the work when the remaining work is small enough to be solved easily.</p>
<p>Recursive algorithms, especially ones based on a form of <a href="http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm" target="_blank">divide and conquer</a>, are often a very good candidate for parallelization.</p>
<p> <span id="more-209"></span>
<p>This is apparent from a common sense standpoint.&#160; Since we’re dividing up the total work in the algorithm, we have an obvious, <a href="http://reedcopsey.com/2010/01/26/parallelism-in-net-part-5-partitioning-of-work/" target="_blank">built-in partitioning scheme</a>.&#160; Once partitioned, the data can be worked upon independently, so there is good, clean isolation of data.</p>
<p>Implementing this type of algorithm is fairly simple.&#160; The <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel(VS.100).aspx" target="_blank">Parallel class</a> in .NET 4 includes a method suited for this type of operation: <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.invoke(VS.100).aspx" target="_blank">Parallel.Invoke</a>.&#160; This method works by taking any number of delegates defined as an <a href="http://msdn.microsoft.com/en-us/library/system.action(VS.100).aspx" target="_blank">Action</a>, and operating them all in parallel.&#160; The method returns when every delegate has completed:</p>
<pre class="csharpcode">Parallel.Invoke(
    () =&gt;
        {
            Console.WriteLine(<span class="str">&quot;Action 1 executing in thread {0}&quot;</span>,
                                                 Thread.CurrentThread.ManagedThreadId);
        },
    () =&gt;
        {
            Console.WriteLine(<span class="str">&quot;Action 2 executing in thread {0}&quot;</span>,
                                                 Thread.CurrentThread.ManagedThreadId);
        },
    () =&gt;
        {
            Console.WriteLine(<span class="str">&quot;Action 3 executing in thread {0}&quot;</span>,
                                                 Thread.CurrentThread.ManagedThreadId);
        }
    );</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Running this simple example demonstrates the ease of using this method.&#160; For example, on my system, I get three separate thread IDs when running the above code.&#160; By allowing any number of delegates to be executed directly, concurrently, the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.invoke(VS.100).aspx" target="_blank">Parallel.Invoke</a> method provides us an easy way to parallelize any algorithm based on <a href="http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm" target="_blank">divide and conquer</a>.&#160; We can divide our work in each step, and execute each task in parallel, recursively.</p>
<p>For example, suppose we wanted to implement our own <a href="http://en.wikipedia.org/wiki/Quicksort" target="_blank">quicksort</a> routine.&#160; The <a href="http://en.wikipedia.org/wiki/Quicksort" target="_blank">quicksort</a> algorithm can be designed based on <a href="http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm" target="_blank">divide and conquer</a>.&#160; In each iteration, we pick a pivot point, and use that to partition the total array.&#160; We swap the elements around the pivot, then recursively sort the lists on each side of the pivot.&#160; </p>
<p>For example, let’s look at this simple, sequential implementation of <a href="http://en.wikipedia.org/wiki/Quicksort" target="_blank">quicksort</a>:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> QuickSort&lt;T&gt;(T[] array) <span class="kwrd">where</span> T : IComparable&lt;T&gt;
{
    QuickSortInternal(array, 0, array.Length - 1);
}

<span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">void</span> QuickSortInternal&lt;T&gt;(T[] array, <span class="kwrd">int</span> left, <span class="kwrd">int</span> right)
    <span class="kwrd">where</span> T : IComparable&lt;T&gt;
{
    <span class="kwrd">if</span> (left &gt;= right)
    {
        <span class="kwrd">return</span>;
    }

    SwapElements(array, left, (left + right) / 2);
    <span class="kwrd">int</span> last = left;
    <span class="kwrd">for</span> (<span class="kwrd">int</span> current = left + 1; current &lt;= right; ++current)
    {
        <span class="kwrd">if</span> (array[current].CompareTo(array[left]) &lt; 0)
        {
            ++last;
            SwapElements(array, last, current);
        }
    }

    SwapElements(array, left, last);

    QuickSortInternal(array, left, last - 1);
    QuickSortInternal(array, last + 1, right);
}

<span class="kwrd">static</span> <span class="kwrd">void</span> SwapElements&lt;T&gt;(T[] array, <span class="kwrd">int</span> i, <span class="kwrd">int</span> j)
{
    T temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}</pre>
<p>Here, we implement <a href="http://en.wikipedia.org/wiki/Quicksort" target="_blank">the quicksort algorithm</a> in a very common, <a href="http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm" target="_blank">divide and conquer</a> approach.&#160; Running this against the built-in <a href="http://msdn.microsoft.com/en-us/library/system.array.sort.aspx" target="_blank">Array.Sort</a> routine shows that we get the exact same answers (although the framework’s sort routine is slightly faster).&#160; On my system, for example, I can use framework’s sort to sort ten million random doubles in about 7.3s, and this implementation takes about 9.3s on average.</p>
<p>Looking at this routine, though, there is a clear opportunity to parallelize.&#160; At the end of QuickSortInternal, we recursively call into QuickSortInternal with each partition of the array after the pivot is chosen.&#160; This can be rewritten to use <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.invoke(VS.100).aspx" target="_blank">Parallel.Invoke</a> by simply changing it to:</p>
<pre class="csharpcode">    <span class="rem">// Code above is unchanged...</span>
    SwapElements(array, left, last);

    Parallel.Invoke(
        () =&gt; QuickSortInternal(array, left, last - 1),
        () =&gt; QuickSortInternal(array, last + 1, right)
    );
}</pre>
<p>This routine will now run in parallel.&#160; When executing, we now see the CPU usage across all cores spike while it executes.&#160; </p>
<p>However, there is a significant problem here – by parallelizing this routine, we took it from an execution time of 9.3s to an execution time of approximately <strong>14 seconds!</strong>&#160; We’re using more resources as seen in the CPU usage, but the overall result is a dramatic slowdown in overall processing time.</p>
<p>This occurs because parallelization adds overhead.&#160; Each time we split this array, we spawn two new tasks to parallelize this algorithm!&#160; This is far, far too many tasks for our cores to operate upon at a single time.&#160; In effect, we’re “over-parallelizing” this routine.&#160; This is a common problem when working with <a href="http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm" target="_blank">divide and conquer</a> algorithms, and leads to an important observation:</p>
<p><strong>When parallelizing a recursive routine, take special care not to add more tasks than necessary to fully utilize your system.</strong></p>
<p>This can be done with a few different approaches, in this case.&#160; Typically, the way to handle this is to stop parallelizing the routine at a certain point, and revert back to the serial approach.&#160; Since the first few recursions will all still be parallelized, our “deeper” recursive tasks will be running in parallel, and can take full advantage of the machine.&#160; This also dramatically reduces the overhead added by parallelizing, since we’re only adding overhead for the first few recursive calls.&#160; </p>
<p>There are two basic approaches we can take here.&#160; The first approach would be to look at the total work size, and if it’s smaller than a specific threshold, revert to our serial implementation.&#160; In this case, we could just check right-left, and if it’s under a threshold, call the methods directly instead of using Parallel.Invoke.</p>
<p>The second approach is to track how “deep” in the “tree” we are currently at, and if we are below some number of levels, stop parallelizing.&#160; This approach is a more general-purpose approach, since it works on routines which parse trees as well as routines working off of a single array, but may not work as well if a poor partitioning strategy is chosen or the tree is not balanced evenly.</p>
<p>This can be written very easily.&#160; If we pass a <em>maxDepth</em> parameter into our internal routine, we can restrict the amount of times we parallelize by changing the recursive call to:</p>
<pre class="csharpcode"><span class="rem">// Code above is unchanged...</span>
SwapElements(array, left, last);

<span class="kwrd">if</span> (maxDepth &lt; 1)
{
    QuickSortInternal(array, left, last - 1, maxDepth);
    QuickSortInternal(array, last + 1, right, maxDepth);
}
<span class="kwrd">else</span>
{
    --maxDepth;
    Parallel.Invoke(
        () =&gt; QuickSortInternal(array, left, last - 1, maxDepth),
        () =&gt; QuickSortInternal(array, last + 1, right, maxDepth));
}</pre>
<p>We no longer allow this to parallelize indefinitely – only to a specific depth, at which time we revert to a serial implementation.&#160; By starting the routine with a maxDepth equal to <a href="http://msdn.microsoft.com/en-us/library/system.environment.processorcount.aspx" target="_blank">Environment.ProcessorCount</a>, we can restrict the total amount of parallel operations significantly, but still provide adequate work for each processing core.</p>
<p>With this final change, my timings are much better.&#160; On average, I get the following timings:</p>
<ul>
<li>Framework via Array.Sort: 7.3 seconds </li>
<li>Serial Quicksort Implementation: 9.3 seconds </li>
<li>Naive Parallel Implementation: 14 seconds </li>
<li>Parallel Implementation Restricting Depth: <strong>4.7 seconds</strong> </li>
</ul>
<p>Finally, we are now faster than the framework’s Array.Sort implementation.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/RMA0PRiyyAE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/02/26/parallelism-in-net-part-11-divide-and-conquer-via-parallel-invoke/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/02/26/parallelism-in-net-part-11-divide-and-conquer-via-parallel-invoke/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 10, Cancellation in PLINQ and the Parallel class</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/Ry8_2Zq1OM4/</link>
		<comments>http://reedcopsey.com/2010/02/17/parallelism-in-net-part-10-cancellation-in-plinq-and-the-parallel-class/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 01:35:29 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>
		<category><![CDATA[PLINQ]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/02/17/parallelism-in-net-part-10-cancellation-in-plinq-and-the-parallel-class/</guid>
		<description><![CDATA[Many routines are parallelized because they are long running processes.&#160; When writing an algorithm that will run for a long period of time, its typically a good practice to allow that routine to be cancelled.&#160; I previously discussed terminating a parallel loop from within, but have not demonstrated how a routine can be cancelled from [...]]]></description>
			<content:encoded><![CDATA[<p>Many routines are parallelized because they are long running processes.&#160; When writing an algorithm that will run for a long period of time, its typically a good practice to allow that routine to be cancelled.&#160; I previously discussed <a href="http://reedcopsey.com/2010/01/22/parallelism-in-net-part-3-imperative-data-parallelism-early-termination/" target="_blank">terminating a parallel loop from within</a>, but have not demonstrated how a routine can be cancelled from the caller’s perspective.&#160; Cancellation in <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> and the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> is handled through a new, <a href="http://msdn.microsoft.com/en-us/library/dd997364(VS.100).aspx" target="_blank">unified cooperative cancellation model</a> introduced with .NET 4.0.</p>
<p> <span id="more-206"></span>
<p>Cancellation in .NET 4 is based around a new, lightweight struct called <a href="http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken(VS.100).aspx" target="_blank">CancellationToken</a>.&#160; A <a href="http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken(VS.100).aspx" target="_blank">CancellationToken</a> is a small, thread-safe value type which is generated via a <a href="http://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource(VS.100).aspx" target="_blank">CancellationTokenSource</a>.&#160; There are many goals which led to this design.&#160; For our purposes, we will focus on a couple of specific design decisions:</p>
<ul>
<li>Cancellation is cooperative.&#160; A calling method can request a cancellation, but it’s up to the processing routine to terminate &#8211; it is not forced.</li>
<li>Cancellation is consistent.&#160; A single method call requests a cancellation on every copied CancellationToken in the routine.</li>
</ul>
<p>Let’s begin by looking at how we can cancel a <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> query.&#160; Supposed we wanted to provide the option to cancel our <a href="http://reedcopsey.com/2010/01/26/parallelism-in-net-part-6-declarative-data-parallelism/" target="_blank">query from Part 6</a>:</p>
<pre class="csharpcode"><span class="kwrd">double</span> min = collection
                .AsParallel()
                .Min(item =&gt; item.PerformComputation());</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>We would rewrite this to allow for cancellation by adding a call to <a href="http://msdn.microsoft.com/en-us/library/dd413259(VS.100).aspx" target="_blank">ParallelEnumerable.WithCancellation</a> as follows:</p>
<pre class="csharpcode">var cts = <span class="kwrd">new</span> CancellationTokenSource();

<span class="rem">// Pass cts here to a routine that could, </span>
<span class="rem">// in parallel, request a cancellation</span>

<span class="kwrd">try</span>
{
    <span class="kwrd">double</span> min = collection
                    .AsParallel()
                    .WithCancellation(cts.Token)
                    .Min(item =&gt; item.PerformComputation());
}
<span class="kwrd">catch</span> (OperationCanceledException e)
{
    <span class="rem">// Query was cancelled before it finished</span>
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Here, if the user calls <a href="http://msdn.microsoft.com/en-us/library/dd321955(VS.100).aspx" target="_blank">cts.Cancel()</a> before the PLINQ query completes, the query will stop processing, and an <a href="http://msdn.microsoft.com/en-us/library/system.operationcanceledexception.aspx" target="_blank">OperationCanceledException</a> will be raised.&#160; </p>
<p>Be aware, however, that cancellation will not be instantaneous.&#160; When cts.Cancel() is called, the query will only stop after the current item.PerformComputation() elements all finish processing.&#160; cts.Cancel() will prevent PLINQ from scheduling a new task for a new element, but will not stop items which are currently being processed.&#160; This goes back to the first goal I mentioned – Cancellation is cooperative.&#160; Here, we’re requesting the cancellation, but it’s up to PLINQ to terminate.</p>
<p>If we wanted to allow cancellation to occur within our routine, we would need to change our routine to accept a <a href="http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken(VS.100).aspx" target="_blank">CancellationToken</a>, and modify it to handle this specific case:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> PerformComputation(CancellationToken token)
{
    <span class="kwrd">for</span> (<span class="kwrd">int</span> i=0; i&lt;<span class="kwrd">this</span>.iterations; ++i)
    {
        <span class="rem">// Add a check to see if we've been canceled</span>
        <span class="rem">// If a cancel was requested, we'll throw here</span>
        token.ThrowIfCancellationRequested();

        <span class="rem">// Do our processing now</span>
        <span class="kwrd">this</span>.RunIteration(i);
    }
}</pre>
<p>With this overload of PerformComputation, each internal iteration checks to see if a cancellation request was made, and will throw an <a href="http://msdn.microsoft.com/en-us/library/system.operationcanceledexception.aspx" target="_blank">OperationCanceledException</a> at that point, instead of waiting until the method returns.&#160; This is good, since it allows us, as developers, to plan for cancellation, and terminate our routine in a clean, safe state. </p>
<p>This is handled by changing our PLINQ query to:</p>
<pre class="csharpcode"><span class="kwrd">try</span>
{
    <span class="kwrd">double</span> min = collection
                    .AsParallel()
                    .WithCancellation(cts.Token)
                    .Min(item =&gt; item.PerformComputation(cts.Token));
}
<span class="kwrd">catch</span> (OperationCanceledException e)
{
    <span class="rem">// Query was cancelled before it finished</span>
}</pre>
<p><a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> is very good about handling this exception, as well.&#160; There is a very good chance that multiple items will raise this exception, since the entire purpose of PLINQ is to have multiple items be processed concurrently.&#160; <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> will take all of the <a href="http://msdn.microsoft.com/en-us/library/system.operationcanceledexception.aspx" target="_blank">OperationCanceledException</a> instances raised within these methods, and merge them into a single <a href="http://msdn.microsoft.com/en-us/library/system.operationcanceledexception.aspx" target="_blank">OperationCanceledException</a> in the call stack.&#160; This is done internally because we added the call to <a href="http://msdn.microsoft.com/en-us/library/dd413259(VS.100).aspx" target="_blank">ParallelEnumerable.WithCancellation</a>.</p>
<p>If, however, a different exception is raised by any of the elements, the <a href="http://msdn.microsoft.com/en-us/library/system.operationcanceledexception.aspx" target="_blank">OperationCanceledException</a> as well as the other Exception will be merged into a single <a href="http://msdn.microsoft.com/en-us/library/system.aggregateexception(VS.100).aspx" target="_blank">AggregateException</a>.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> uses the same cancellation model, as well.&#160; Here, we supply our <a href="http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken(VS.100).aspx" target="_blank">CancellationToken</a> as part of the <a href="http://reedcopsey.com/2010/02/11/parallelism-in-net-part-9-configuration-in-plinq-and-tpl/" target="_blank">configuration</a>.&#160; The <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions(VS.100).aspx" target="_blank">ParallelOptions class</a> contains a property for the <a href="http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken(VS.100).aspx" target="_blank">CancellationToken</a>.&#160; This allows us to cancel a <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.for(VS.100).aspx" target="_blank">Parallel.For</a> or <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.foreach(VS.100).aspx" target="_blank">Parallel.ForEach</a> routine in a very similar manner to our PLINQ query.&#160; As an example, we could rewrite our <a href="http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/" target="_blank">Parallel.ForEach loop from Part 2</a> to support cancellation by changing it to:</p>
<pre class="csharpcode"><span class="kwrd">try</span>
{
    var cts = <span class="kwrd">new</span> CancellationTokenSource();
    var options = <span class="kwrd">new</span> ParallelOptions()
                      {
                          CancellationToken = cts.Token
                      };
    Parallel.ForEach(customers, options, customer =&gt;
    {
        <span class="rem">// Run some process that takes some time...</span>
        DateTime lastContact = theStore.GetLastContact(customer);
        TimeSpan timeSinceContact = DateTime.Now - lastContact;

        <span class="rem">// Check for cancellation here</span>
        options.CancellationToken.ThrowIfCancellationRequested();

        <span class="rem">// If it's been more than two weeks, send an email, and update...</span>
        <span class="kwrd">if</span> (timeSinceContact.Days &gt; 14)
        {
           theStore.EmailCustomer(customer);
           customer.LastEmailContact = DateTime.Now;
        }
    });
}
<span class="kwrd">catch</span> (OperationCanceledException e)
{
    <span class="rem">// The loop was cancelled</span>
}</pre>
<p>Notice that here we use the same approach taken in <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a>.&#160; The <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> will automatically handle our cancellation in the same manner as PLINQ, providing a clean, unified model for cancellation of any parallel routine.&#160; The TPL performs the same aggregation of the cancellation exceptions as PLINQ, as well, which is why a single exception handler for OperationCanceledException will cleanly handle this scenario.&#160; This works because we’re using the same CancellationToken provided in the ParallelOptions.&#160; If a different exception was thrown by one thread, or a CancellationToken from a different CancellationTokenSource was used to raise our exception, we would instead receive all of our individual exceptions merged into one <a href="http://msdn.microsoft.com/en-us/library/system.aggregateexception(VS.100).aspx" target="_blank">AggregateException</a>.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/Ry8_2Zq1OM4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/02/17/parallelism-in-net-part-10-cancellation-in-plinq-and-the-parallel-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/02/17/parallelism-in-net-part-10-cancellation-in-plinq-and-the-parallel-class/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 9, Configuration in PLINQ and TPL</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/6f5wyIlH104/</link>
		<comments>http://reedcopsey.com/2010/02/11/parallelism-in-net-part-9-configuration-in-plinq-and-tpl/#comments</comments>
		<pubDate>Fri, 12 Feb 2010 01:12:42 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>
		<category><![CDATA[PLINQ]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/02/11/parallelism-in-net-part-9-configuration-in-plinq-and-tpl/</guid>
		<description><![CDATA[Parallel LINQ and the Task Parallel Library contain many options for configuration.&#160; Although the default configuration options are often ideal, there are times when customizing the behavior is desirable.&#160; Both frameworks provide full configuration support.
 
When working with Data Parallelism, there is one primary configuration option we often need to control – the number of [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">Parallel LINQ</a> and the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> contain many options for configuration.&#160; Although the default configuration options are often ideal, there are times when customizing the behavior is desirable.&#160; Both frameworks provide full configuration support.</p>
<p> <span id="more-203"></span>
<p>When working with <a href="http://msdn.microsoft.com/en-us/library/dd537608(VS.100).aspx">Data Parallelism</a>, there is one primary configuration option we often need to control – the number of threads we want the system to use when parallelizing our routine.&#160; By default, PLINQ and the TPL both use the ThreadPool to schedule tasks.&#160; Given the <a href="http://www.danielmoth.com/Blog/2008/11/new-and-improved-clr-4-thread-pool.html" target="_blank">major improvements in the ThreadPool in CLR 4</a>, this default behavior is often ideal.&#160; </p>
<p>However, there are times that the default behavior is not appropriate.&#160; For example, if you are working on multiple threads simultaneously, and want to schedule parallel operations from within both threads, you might want to consider restricting each parallel operation to using a subset of the processing cores of the system.&#160; Not doing this might over-parallelize your routine, which leads to inefficiencies from having too many context switches.</p>
<p>In the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a>, configuration is handled via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions(VS.100).aspx" target="_blank">ParallelOptions class</a>.&#160; All of the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel_methods(VS.100).aspx" target="_blank">methods of the Parallel class</a> have an overload which accepts a <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions(VS.100).aspx" target="_blank">ParallelOptions</a> argument.</p>
<p>We configure the Parallel class by setting the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions.maxdegreeofparallelism(VS.100).aspx" target="_blank">ParallelOptions.MaxDegreeOfParallelism</a> property.&#160; For example, let’s revisit one of the simple data parallel examples from <a href="http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/" target="_blank">Part 2</a>:</p>
<pre class="csharpcode">Parallel.For(0, pixelData.GetUpperBound(0), row =&gt;
{
    <span class="kwrd">for</span> (<span class="kwrd">int</span> col=0; col &lt; pixelData.GetUpperBound(1); ++col)
    {
        pixelData[row, col] = AdjustContrast(pixelData[row, col], minPixel, maxPixel);
    }
});</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Here, we’re looping through an image, and calling a method on each pixel in the image.&#160; If this was being done on a separate thread, and we knew another thread within our system was going to be doing a similar operation, we likely would want to restrict this to using half of the cores on the system.&#160; This could be accomplished easily by doing:</p>
<pre class="csharpcode">var options = <span class="kwrd">new</span> ParallelOptions();
options.MaxDegreeOfParallelism = Math.Max(Environment.ProcessorCount / 2, 1);

Parallel.For(0, pixelData.GetUpperBound(0), options, row =&gt;
{
    <span class="kwrd">for</span> (<span class="kwrd">int</span> col=0; col &lt; pixelData.GetUpperBound(1); ++col)
    {
        pixelData[row, col] = AdjustContrast(pixelData[row, col], minPixel, maxPixel);
    }
});</pre>
<p>Now, we’re restricting this routine to using no more than half the cores in our system.&#160; Note that I included a check to prevent a single core system from supplying zero; without this check, we’d potentially cause an exception.&#160; I also did not hard code a specific value for the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions.maxdegreeofparallelism(VS.100).aspx" target="_blank">MaxDegreeOfParallelism</a> property.&#160; One of our goals when parallelizing a routine is allowing it to scale on better hardware.&#160; Specifying a hard-coded value would contradict that goal.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">Parallel LINQ</a> also supports configuration, and in fact, has quite a few more options for configuring the system.&#160; The main configuration option we most often need is the same as our TPL option: we need to supply the maximum number of processing threads.&#160; In <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a>, this is done via a new extension method on ParallelQuery&lt;T&gt;: <a href="http://msdn.microsoft.com/en-us/library/dd383719(VS.100).aspx" target="_blank">ParallelEnumerable.WithDegreeOfParallelism</a>.</p>
<p>Let’s revisit our <a href="http://reedcopsey.com/2010/01/26/parallelism-in-net-part-6-declarative-data-parallelism/" target="_blank">declarative data parallelism sample from Part 6</a>:</p>
<pre class="csharpcode"><span class="kwrd">double</span> min = collection.AsParallel().Min(item =&gt; item.PerformComputation());</pre>
<p>Here, we’re performing a computation on each element in the collection, and saving the minimum value of this operation.&#160; If we wanted to restrict this to a limited number of threads, we would add our new extension method:</p>
<pre class="csharpcode"><span class="kwrd">int</span> maxThreads = Math.Max(Environment.ProcessorCount / 2, 1);
<span class="kwrd">double</span> min = collection
                 .AsParallel()
                 .WithDegreeOfParallelism(maxThreads)
                 .Min(item =&gt; item.PerformComputation());</pre>
<p>This automatically restricts the <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> query to half of the threads on the system.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> provides some additional configuration options.&#160; By default, PLINQ will occasionally revert to processing a query in parallel.&#160; This occurs because many queries, if parallelized, typically actually cause an overall slowdown compared to a serial processing equivalent.&#160; By analyzing the “shape” of the query, PLINQ often decides to run a query serially instead of in parallel.&#160; This can occur for (<a href="http://msdn.microsoft.com/en-us/library/dd997399(VS.100).aspx" target="_blank">taken from MSDN</a>):</p>
<ul>
<li>Queries that contain a Select, indexed Where, indexed SelectMany, or ElementAt clause after an ordering or filtering operator that has removed or rearranged original indices. </li>
<li>Queries that contain a Take, TakeWhile, Skip, SkipWhile operator and where indices in the source sequence are not in the original order. </li>
<li>Queries that contain Zip or SequenceEquals, unless one of the data sources has an originally ordered index and the other data source is indexable (i.e. an array or IList(T)). </li>
<li>Queries that contain Concat, unless it is applied to indexable data sources. </li>
<li>Queries that contain Reverse, unless applied to an indexable data source. </li>
</ul>
<p>If the specific query follows these rules, PLINQ will run the query on a single thread.&#160; However, none of these rules look at the specific work being done in the delegates, only at the “shape” of the query.&#160; There are cases where running in parallel may still be beneficial, even if the shape is one where it typically parallelizes poorly.&#160; In these cases, you can override the default behavior by using the <a href="http://msdn.microsoft.com/en-us/library/dd642145(VS.100).aspx" target="_blank">WithExecutionMode</a> extension method.&#160; This would be done like so:</p>
<pre class="csharpcode">var reversed = collection
                  .AsParallel()
                  .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                  .Select(i =&gt; i.PerformComputation())
                  .Reverse();</pre>
<p>Here, the default behavior would be to not parallelize the query unless collection implemented IList&lt;T&gt;.&#160; We can force this to run in parallel by adding the <a href="http://msdn.microsoft.com/en-us/library/dd642145(VS.100).aspx" target="_blank">WithExecutionMode</a> extension method in the method chain.</p>
<p>Finally, <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> has the ability to configure how results are returned.&#160; When a query is filtering or selecting an input collection, the results will need to be streamed back into a single IEnumerable&lt;T&gt; result.&#160; For example, the method above returns a new, reversed collection.&#160; In this case, the processing of the collection will be done in parallel, but the results need to be streamed back to the caller serially, so they can be enumerated on a single thread.</p>
<p>This streaming introduces overhead.&#160; IEnumerable&lt;T&gt; isn’t designed with thread safety in mind, so the system needs to handle merging the parallel processes back into a single stream, which introduces synchronization issues.&#160; There are two extremes of how this could be accomplished, but both extremes have disadvantages.</p>
<p>The system could watch each thread, and whenever a thread produces a result, take that result and send it back to the caller.&#160; This would mean that the calling thread would have access to the data as soon as data is available, which is the benefit of this approach.&#160; However, it also means that every item is introducing synchronization overhead, since each item needs to be merged individually.</p>
<p>On the other extreme, the system could wait until all of the results from all of the threads were ready, then push all of the results back to the calling thread in one shot.&#160; The advantage here is that the least amount of synchronization is added to the system, which means the query will, on a whole, run the fastest.&#160; However, the calling thread will have to wait for all elements to be processed, so this could introduce a long delay between when a parallel query begins and when results are returned.</p>
<p>The default behavior in <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> is actually between these two extremes.&#160; By default, PLINQ maintains an internal buffer, and chooses an optimal buffer size to maintain.&#160; Query results are accumulated into the buffer, then returned in the IEnumerable&lt;T&gt; result in chunks.&#160; This provides reasonably fast access to the results, as well as good overall throughput, in most scenarios.</p>
<p>However, if we know the nature of our algorithm, we may decide we would prefer one of the other extremes.&#160; This can be done by using the <a href="http://msdn.microsoft.com/en-us/library/dd438099(VS.100).aspx" target="_blank">WithMergeOptions</a> extension method.&#160; For example, if we know that our PerformComputation() routine is very slow, but also variable in runtime, we may want to retrieve results as they are available, with no bufferring.&#160; This can be done by changing our above routine to:</p>
<pre class="csharpcode">var reversed = collection
                  .AsParallel()
                  .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                  .WithMergeOptions(ParallelMergeOptions.NotBuffered)
                  .Select(i =&gt; i.PerformComputation())
                  .Reverse();</pre>
<p>On the other hand, if are already on a background thread, and we want to allow the system to maximize its speed, we might want to allow the system to fully buffer the results:</p>
<pre class="csharpcode">var reversed = collection
                  .AsParallel()
                  .WithExecutionMode(ParallelExecutionMode.ForceParallelism)
                  .WithMergeOptions(ParallelMergeOptions.FullyBuffered)
                  .Select(i =&gt; i.PerformComputation())
                  .Reverse();</pre>
<p>Notice, also, that you can specify multiple configuration options in a parallel query.&#160; By chaining these extension methods together, we generate a query that will always run in parallel, and will always complete before making the results available in our IEnumerable&lt;T&gt;.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/6f5wyIlH104" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/02/11/parallelism-in-net-part-9-configuration-in-plinq-and-tpl/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/02/11/parallelism-in-net-part-9-configuration-in-plinq-and-tpl/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 8, PLINQ’s ForAll Method</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/dx0dohKxN38/</link>
		<comments>http://reedcopsey.com/2010/02/03/parallelism-in-net-part-8-plinqs-forall-method/#comments</comments>
		<pubDate>Thu, 04 Feb 2010 01:56:25 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>
		<category><![CDATA[PLINQ]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/02/03/parallelism-in-net-part-8-plinqs-forall-method/</guid>
		<description><![CDATA[Parallel LINQ extends LINQ to Objects, and is typically very similar.&#160; However, as I previously discussed, there are some differences.&#160; Although the standard way to handle simple Data Parellelism is via Parallel.ForEach, it’s possible to do the same thing via PLINQ. 
PLINQ adds a new method unavailable in standard LINQ which provides new functionality…
 
LINQ [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">Parallel LINQ</a> extends <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ to Objects</a>, and is typically very similar.&#160; However, as I previously discussed, there are <a href="http://reedcopsey.com/2010/01/28/parallelism-in-net-part-7-some-differences-between-plinq-and-linq-to-objects/" target="_blank">some differences</a>.&#160; Although the standard way to handle <a href="http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/" target="_blank">simple Data Parellelism is via Parallel.ForEach</a>, it’s possible to do the same thing via PLINQ. </p>
<p>PLINQ adds a new method unavailable in standard LINQ which provides new functionality…</p>
<p> <span id="more-173"></span>
<p><a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ</a> is designed to provide a much simpler way of handling querying, including filtering, ordering, grouping, and many other benefits.&#160; Reading the description in <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ to Objects on MSDN</a>, it becomes clear that the thinking behind LINQ deals with retrieval of data.&#160; LINQ works by adding a <a href="http://en.wikipedia.org/wiki/Functional_programming" target="_blank">functional programming</a> style on top of .NET, allowing us to express filters in terms of predicate functions, for example.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> is, generally, very similar.&#160; Typically, when using PLINQ, we write declarative statements to <a href="http://reedcopsey.com/2010/01/26/parallelism-in-net-part-6-declarative-data-parallelism/" target="_blank">filter a dataset or perform an aggregation.</a>&#160; However, PLINQ adds one new method, which provides a very different purpose: <a href="http://msdn.microsoft.com/en-us/library/dd383744(VS.100).aspx" target="_blank">ForAll</a>.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/dd383744(VS.100).aspx" target="_blank">ForAll</a> method is defined on <a href="http://msdn.microsoft.com/en-us/library/system.linq.parallelenumerable(VS.100).aspx" target="_blank">ParallelEnumerable</a>, and will work upon any <a href="http://msdn.microsoft.com/en-us/library/dd383736(VS.100).aspx" target="_blank">ParallelQuery&lt;T&gt;</a>.&#160; Unlike the sequence operators in LINQ and PLINQ, ForAll is<strong> intended to cause side effects</strong>.&#160; It does not filter a collection, but rather invokes an action on each element of the collection.</p>
<p>At first glance, this seems like a bad idea.&#160; For example, <a href="http://blogs.msdn.com/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx" target="_blank">Eric Lippert clearly explained two philosophical objections to providing an IEnumerable&lt;T&gt;.ForEach extension method</a>, one of which still applies when parallelized.&#160; The sole purpose of this method is to cause side effects, and as such, I agree that the <a href="http://msdn.microsoft.com/en-us/library/dd383744(VS.100).aspx" target="_blank">ForAll</a> method “<em>violates the functional programming principles that all the other sequence operators are based upon</em>”, in exactly the same manner an IEnumerable&lt;T&gt;.ForEach extension method would violate these principles.&#160; Eric Lippert’s second reason for disliking a ForEach extension method does not necessarily apply to <a href="http://msdn.microsoft.com/en-us/library/dd383744(VS.100).aspx" target="_blank">ForAll</a> – replacing <a href="http://msdn.microsoft.com/en-us/library/dd383744(VS.100).aspx" target="_blank">ForAll</a> with a call to <a href="http://msdn.microsoft.com/en-us/library/dd991870(VS.100).aspx" target="_blank">Parallel.ForEach</a> has the same closure semantics, so there is no loss there.</p>
<p>Although <a href="http://msdn.microsoft.com/en-us/library/dd383744(VS.100).aspx" target="_blank">ForAll</a> may have philosophical issues, there is a pragmatic reason to include this method.&#160; Without <a href="http://msdn.microsoft.com/en-us/library/dd383744(VS.100).aspx" target="_blank">ForAll</a>, we would take a fairly serious performance hit in many situations.&#160; Often, we need to perform some filtering or grouping, then perform an action using the results of our filter.&#160; </p>
<p>Using a standard <a href="http://msdn.microsoft.com/en-us/library/ttw7t8t6(VS.100).aspx" target="_blank">foreach statement</a> to perform our action would avoid this philosophical issue:</p>
<pre class="csharpcode"><span class="rem">// Filter our collection</span>
var filteredItems = collection.AsParallel().Where( i =&gt; i.SomePredicate() );

<span class="rem">// Now perform an action</span>
<span class="kwrd">foreach</span> (var item <span class="kwrd">in</span> filteredItems)
{
    <span class="rem">// These will now run serially</span>
    item.DoSomething();
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This would cause a loss in performance, since we lose any parallelism in place, and cause all of our actions to be run serially.</p>
<p>We could easily use a <a href="http://msdn.microsoft.com/en-us/library/dd991870(VS.100).aspx" target="_blank">Parallel.ForEach</a> instead, which adds parallelism to the actions:</p>
<pre class="csharpcode"><span class="rem">// Filter our collection</span>
var filteredItems = collection.AsParallel().Where( i =&gt; i.SomePredicate() );

<span class="rem">// Now perform an action once the filter completes</span>
Parallel.ForEach(filteredItems, item =&gt;
{
    <span class="rem">// These will now run in parallel</span>
    item.DoSomething();
});</pre>
<p>This is a noticeable improvement, since both our filtering and our actions run parallelized.&#160; However, there is still a large bottleneck in place here.&#160; </p>
<p>The problem lies with my comment “<em>perform an action once the filter completes</em>”.&#160; Here, we’re parallelizing the filter, then collecting all of the results, blocking until the filter completes.&#160; Once the filtering of every element is completed, we then <a href="http://reedcopsey.com/2010/01/26/parallelism-in-net-part-5-partitioning-of-work/" target="_blank">repartition</a> the results of the filter, reschedule into multiple threads, and perform the action on each element.&#160; By moving this into two separate statements, we potentially double our parallelization overhead, since we’re forcing the work to be partitioned and scheduled twice as many times.</p>
<p>This is where the pragmatism comes into play.&#160; By <a href="http://blogs.msdn.com/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx" target="_blank">violating our functional principles</a>, we gain the ability to avoid the overhead and cost of rescheduling the work:</p>
<pre class="csharpcode"><span class="rem">// Perform an action on the results of our filter</span>
collection
    .AsParallel()
    .Where( i =&gt; i.SomePredicate() )
    .ForAll( i =&gt; i.DoSomething() );</pre>
<p>The ability to avoid the scheduling overhead is a compelling reason to use <a href="http://msdn.microsoft.com/en-us/library/dd383744(VS.100).aspx" target="_blank">ForAll</a>.&#160; This really goes back to one of the <a href="http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/" target="_blank">key points I discussed in data parallelism</a>: Partition your problem in a way to place the most work possible into each task.&#160; Here, this means leaving the statement attached to the expression, even though it causes side effects and is not standard usage for LINQ.</p>
<p>This leads to my one guideline for using <a href="http://msdn.microsoft.com/en-us/library/dd383744(VS.100).aspx" target="_blank">ForAll</a>:</p>
<p><strong>The ForAll extension method should only be used to process the results of a parallel query, as returned by a PLINQ expression.</strong></p>
<p>Any other usage scenario should use <a href="http://msdn.microsoft.com/en-us/library/dd991870(VS.100).aspx" target="_blank">Parallel.ForEach</a>, instead.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/dx0dohKxN38" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/02/03/parallelism-in-net-part-8-plinqs-forall-method/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/02/03/parallelism-in-net-part-8-plinqs-forall-method/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 7, Some Differences between PLINQ and LINQ to Objects</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/vjUmkNN_QMc/</link>
		<comments>http://reedcopsey.com/2010/01/28/parallelism-in-net-part-7-some-differences-between-plinq-and-linq-to-objects/#comments</comments>
		<pubDate>Thu, 28 Jan 2010 21:02:03 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>
		<category><![CDATA[PLINQ]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/28/parallelism-in-net-part-7-some-differences-between-plinq-and-linq-to-objects/</guid>
		<description><![CDATA[In my previous post on Declarative Data Parallelism, I mentioned that PLINQ extends LINQ to Objects to support parallel operations.&#160; Although nearly all of the same operations are supported, there are some differences between PLINQ and LINQ to Objects.&#160; By introducing Parallelism to our declarative model, we add some extra complexity.&#160; This, in turn, adds [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://reedcopsey.com/2010/01/26/parallelism-in-net-part-6-declarative-data-parallelism/" target="_blank">previous post on Declarative Data Parallelism</a>, I mentioned that <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> extends <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ to Objects</a> to support parallel operations.&#160; Although nearly all of the same operations are supported, there are some differences between PLINQ and LINQ to Objects.&#160; By introducing Parallelism to our declarative model, we add some extra complexity.&#160; This, in turn, adds some extra requirements that must be addressed.</p>
<p>In order to illustrate the main differences, and why they exist, let’s begin by discussing some differences in how the two technologies operate, and look at the underlying types involved in <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ to Objects</a> and <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> .</p>
<p> <span id="more-166"></span>
<p><a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ to Objects</a> is mainly built upon a single class: <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx" target="_blank">Enumerable</a>.&#160; The <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx" target="_blank">Enumerable class</a> is a static class that defines a large set of <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods.aspx" target="_blank">extension methods</a>, nearly all of which work upon an <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a>.&#160; Many of these methods return a new <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a>, allowing the methods to be chained together into a <a href="http://en.wikipedia.org/wiki/Fluent_interface" target="_blank">fluent style interface</a>.&#160; This is what allows us to write statements that chain together, and lead to the nice declarative programming model of LINQ:</p>
<pre class="csharpcode"><span class="kwrd">double</span> min = collection
                .Where(item =&gt; item.SomeProperty &gt; 6 &amp;&amp; item.SomeProperty &lt; 24)
                .Min(item =&gt; item.PerformComputation());</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p><a href="http://msdn.microsoft.com/en-us/library/bb397926.aspx" target="_blank">Other LINQ variants</a> work in a similar fashion.&#160; For example, most data-oriented LINQ providers are built upon an implementation of <a href="http://msdn.microsoft.com/en-us/library/bb351562.aspx" target="_blank">IQueryable&lt;T&gt;</a>, which allows the database provider to turn a LINQ statement into an underlying SQL query, to be performed directly on the remote database.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> is similar, but instead of being built upon the <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx" target="_blank">Enumerable class</a>, most of <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> is built upon a new static class: <a href="http://msdn.microsoft.com/en-us/library/system.linq.parallelenumerable(VS.100).aspx" target="_blank">ParallelEnumerable</a>.&#160; When using <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a>, you typically begin with any collection which implements <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a>, and convert it to a new type using an extension method defined on ParallelEnumerable: <a href="http://msdn.microsoft.com/en-us/library/dd413602(VS.100).aspx" target="_blank">AsParallel()</a>.&#160; This method takes any <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a>, and converts it into a <a href="http://msdn.microsoft.com/en-us/library/dd383736(VS.100).aspx" target="_blank">ParallelQuery&lt;T&gt;</a>, the core class for PLINQ.&#160; There is a similar <a href="http://msdn.microsoft.com/en-us/library/system.linq.parallelquery(VS.100).aspx" target="_blank">ParallelQuery</a> class for working with non-generic IEnumerable implementations.</p>
<p>This brings us to our first subtle, but important difference between PLINQ and LINQ – </p>
<p><strong>PLINQ always works upon specific types, which must be explicitly created.</strong> </p>
<p>Typically, the type you’ll use with PLINQ is <a href="http://msdn.microsoft.com/en-us/library/dd413700(VS.100).aspx" target="_blank">ParallelQuery&lt;T&gt;</a>, but it can sometimes be a <a href="http://msdn.microsoft.com/en-us/library/system.linq.parallelquery(VS.100).aspx" target="_blank">ParallelQuery</a> or an <a href="http://msdn.microsoft.com/en-us/library/dd413755(VS.100).aspx" target="_blank">OrderedParallelQuery&lt;T&gt;</a>.&#160; Instead of dealing with an interface, implemented by an unknown class, we’re dealing with a specific class type.&#160; This works seamlessly from a usage standpoint &#8211; <a href="http://msdn.microsoft.com/en-us/library/dd413700(VS.100).aspx" target="_blank">ParallelQuery&lt;T&gt;</a> implements <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a>, so you can always “switch back” to an <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a>.&#160; </p>
<p>The difference only arises at the beginning of our parallelization.&#160; When we’re using LINQ, and we want to process a normal collection via PLINQ, we need to explicitly convert the collection into a <a href="http://msdn.microsoft.com/en-us/library/dd413700(VS.100).aspx" target="_blank">ParallelQuery&lt;T&gt;</a> by calling <a href="http://msdn.microsoft.com/en-us/library/dd413602(VS.100).aspx" target="_blank">AsParallel()</a>.&#160; There is an important consideration here – <a href="http://msdn.microsoft.com/en-us/library/dd413602(VS.100).aspx" target="_blank">AsParallel()</a> does not need to be called on your specific collection, but rather any <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a>.&#160; This allows you to place it anywhere in the chain of methods involved in a LINQ statement, not just at the beginning.&#160; This can be useful if you have an operation which will not parallelize well or is not thread safe.&#160; For example, the following is perfectly valid, and similar to our previous examples:</p>
<pre class="csharpcode"><span class="kwrd">double</span> min = collection
                .AsParallel()
                .Select(item =&gt; item.SomeOperation())
                .Where(item =&gt; item.SomeProperty &gt; 6 &amp;&amp; item.SomeProperty &lt; 24)
                .Min(item =&gt; item.PerformComputation());</pre>
<p>However, if <em>SomeOperation()</em> is not thread safe, we could just as easily do:</p>
<pre class="csharpcode"><span class="kwrd">double</span> min = collection
                .Select(item =&gt; item.SomeOperation())
                .AsParallel()
                .Where(item =&gt; item.SomeProperty &gt; 6 &amp;&amp; item.SomeProperty &lt; 24)
                .Min(item =&gt; item.PerformComputation());</pre>
<p>In this case, we’re using standard <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ to Objects</a> for the <a href="http://msdn.microsoft.com/en-us/library/bb548891.aspx" target="_blank">Select(…)</a> method, then converting the results of that map routine to a <a href="http://msdn.microsoft.com/en-us/library/dd413700(VS.100).aspx" target="_blank">ParallelQuery&lt;T&gt;</a>, and processing our filter (the <a href="http://msdn.microsoft.com/en-us/library/dd384150(VS.100).aspx" target="_blank">Where</a> method) and our aggregation (the <a href="http://msdn.microsoft.com/en-us/library/dd383728(VS.100).aspx" target="_blank">Min</a> method) in parallel.</p>
<p>PLINQ also provides us with a way to convert a <a href="http://msdn.microsoft.com/en-us/library/dd413700(VS.100).aspx" target="_blank">ParallelQuery&lt;T&gt;</a> back into a standard <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a>, forcing sequential processing via standard <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ to Objects</a>.&#160; If <em>SomeOperation() </em>was thread-safe, but <em>PerformComputation()</em> was not thread-safe, we would need to handle this by using the <a href="http://msdn.microsoft.com/en-us/library/dd413587(VS.100).aspx" target="_blank">AsEnumerable()</a> method:</p>
<pre class="csharpcode"><span class="kwrd">double</span> min = collection
                .AsParallel()
                .Select(item =&gt; item.SomeOperation())
                .Where(item =&gt; item.SomeProperty &gt; 6 &amp;&amp; item.SomeProperty &lt; 24)
                .AsEnumerable()
                .Min(item =&gt; item.PerformComputation());</pre>
<p>Here, we’re converting our collection into a <a href="http://msdn.microsoft.com/en-us/library/dd413700(VS.100).aspx" target="_blank">ParallelQuery&lt;T&gt;,</a> doing our map operation (the <a href="http://msdn.microsoft.com/en-us/library/bb548891.aspx" target="_blank">Select(…)</a> method) and our filtering in parallel, then converting the collection back into a standard <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a>, which causes our aggregation via Min() to be performed sequentially.</p>
<p>This could also be written as two statements, as well, which would allow us to use the language integrated syntax for the first portion:</p>
<pre class="csharpcode">var tempCollection = from item <span class="kwrd">in</span> collection.AsParallel()
                     let e = item.SomeOperation()
                     <span class="kwrd">where</span> (e.SomeProperty &gt; 6 &amp;&amp; e.SomeProperty &lt; 24)
                     select e;
<span class="kwrd">double</span> min = tempCollection.AsEnumerable().Min(item =&gt; item.PerformComputation());</pre>
<p>This allows us to use the standard LINQ style language integrated query syntax, but control whether it’s performed in parallel or serial by adding <a href="http://msdn.microsoft.com/en-us/library/dd413602(VS.100).aspx" target="_blank">AsParallel()</a> and <a href="http://msdn.microsoft.com/en-us/library/dd413587(VS.100).aspx" target="_blank">AsEnumerable()</a> appropriately.</p>
<p>The second important difference between PLINQ and LINQ deals with <a href="http://msdn.microsoft.com/en-us/library/dd460677(VS.100).aspx" target="_blank">order preservation</a>.&#160; </p>
<p><strong>PLINQ, by default, does not preserve the order of of source collection.</strong></p>
<p>This is by design.&#160; In order to process a collection in parallel, the system needs to naturally deal with multiple elements at the same time.&#160; Maintaining the original ordering of the sequence adds overhead, which is, in many cases, unnecessary.&#160; Therefore, by default, the system is allowed to completely change the order of your sequence during processing.&#160; If you are doing a standard query operation, this is usually not an issue.&#160; However, there are times when keeping a specific ordering in place is important.&#160; If this is required, you can explicitly request the ordering be preserved throughout all operations done on a <a href="http://msdn.microsoft.com/en-us/library/dd413700(VS.100).aspx" target="_blank">ParallelQuery&lt;T&gt;</a> by using the <a href="http://msdn.microsoft.com/en-us/library/dd413357(VS.100).aspx" target="_blank">AsOrdered()</a> extension method.&#160; This will cause our sequence ordering to be preserved.</p>
<p>For example, suppose we wanted to take a collection, perform an expensive operation which converts it to a new type, and display the first 100 elements.&#160; In <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ to Objects</a>, our code might look something like:</p>
<pre class="csharpcode"><span class="rem">// Using IEnumerable&lt;SourceClass&gt; collection</span>
IEnumerable&lt;ResultClass&gt; results = collection
                                       .Select(e =&gt; e.CreateResult())
                                       .Take(100);</pre>
<p>If we just converted this to a parallel query naively, like so:</p>
<pre class="csharpcode">IEnumerable&lt;ResultClass&gt; results = collection
                                       .AsParallel()
                                       .Select(e =&gt; e.CreateResult())
                                       .Take(100);</pre>
<p>We could very easily get a very different, and non-reproducable, set of results, since the ordering of elements in the input collection is not preserved.&#160; To get the same results as our original query, we need to use:</p>
<pre class="csharpcode">IEnumerable&lt;ResultClass&gt; results = collection
                                       .AsParallel()
                                       .AsOrdered()
                                       .Select(e =&gt; e.CreateResult())
                                       .Take(100);</pre>
<p>This requests that PLINQ process our sequence in a way that verifies that our resulting collection is ordered as if it were processed serially.&#160; This will cause our query to run slower, since there is overhead involved in maintaining the ordering.&#160; However, in this case, it is required, since the ordering is required for correctness.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> is incredibly useful.&#160; It allows us to easily take nearly any <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ to Objects</a> query and run it in parallel, using the same methods and syntax we’ve used previously.&#160; There are some important differences in operation that must be considered, however – it is not a free pass to parallelize everything.&#160; When using PLINQ in order to parallelize your routines declaratively, the same <a href="http://reedcopsey.com/2010/01/22/parallelism-in-net-part-3-imperative-data-parallelism-early-termination/" target="_blank">guideline I mentioned before</a> still applies:</p>
<p><strong>Parallelization is something that should be handled with care and forethought, added by design, and not just introduced casually.</strong></p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/vjUmkNN_QMc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/28/parallelism-in-net-part-7-some-differences-between-plinq-and-linq-to-objects/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/28/parallelism-in-net-part-7-some-differences-between-plinq-and-linq-to-objects/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 6, Declarative Data Parallelism</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/CP2k0Ee2wyI/</link>
		<comments>http://reedcopsey.com/2010/01/26/parallelism-in-net-part-6-declarative-data-parallelism/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 01:26:01 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>
		<category><![CDATA[PLINQ]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/26/parallelism-in-net-part-6-declarative-data-parallelism/</guid>
		<description><![CDATA[When working with a problem that can be decomposed by data, we have a collection, and some operation being performed upon the collection.&#160; I’ve demonstrated how this can be parallelized using the Task Parallel Library and imperative programming using imperative data parallelism via the Parallel class.&#160; While this provides a huge step forward in terms [...]]]></description>
			<content:encoded><![CDATA[<p>When working with a problem that can be <a href="http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/" target="_blank">decomposed by data</a>, we have a collection, and some operation being performed upon the collection.&#160; I’ve demonstrated how this can be parallelized using the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> and <a href="http://en.wikipedia.org/wiki/Imperative_programming" target="_blank">imperative programming</a> using <a href="http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/" target="_blank">imperative data parallelism</a> via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel(VS.100).aspx" target="_blank">Parallel class</a>.&#160; While this provides a huge step forward in terms of power and capabilities, in many cases, <a href="http://reedcopsey.com/2010/01/22/parallelism-in-net-part-4-imperative-data-parallelism-aggregation/" target="_blank">special care must still be given for relative common scenarios</a>.</p>
<p>C# 3.0 and Visual Basic 9.0 introduced a new, <a href="http://en.wikipedia.org/wiki/Declarative_programming" target="_blank">declarative programming model</a> to .NET via the <a href="http://msdn.microsoft.com/en-us/netframework/aa904594.aspx" target="_blank">LINQ Project</a>.&#160; When working with collections, we can now write software that describes <em>what</em> we want to occur without having to explicitly state <em>how </em>the program should accomplish the task.&#160; By taking advantage of <a href="http://msdn.microsoft.com/en-us/netframework/aa904594.aspx" target="_blank">LINQ</a>, many operations become much shorter, more elegant, and easier to understand and maintain.&#160; Version 4.0 of the .NET framework extends this concept into the parallel computation space by introducing <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">Parallel LINQ</a>.</p>
<p> <span id="more-162"></span>
<p>Before we delve into PLINQ, let’s begin with a short discussion of LINQ.&#160; LINQ, the extensions to the .NET Framework which implement language integrated query, set, and transform operations, is <a href="http://msdn.microsoft.com/en-us/library/bb397926.aspx" target="_blank">implemented in many flavors</a>.&#160; For our purposes, we are interested in <a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ to Objects</a>.&#160; When dealing with parallelizing a routine, we typically are dealing with in-memory data storage.&#160; More data-access oriented LINQ variants, such as <a href="http://msdn.microsoft.com/en-us/library/bb386976.aspx" target="_blank">LINQ to SQL</a> and <a href="http://msdn.microsoft.com/en-us/library/aa697427(VS.80).aspx#ado.netenfrmovw_topic4" target="_blank">LINQ to Entities in the Entity Framework</a> fall outside of our concern, since the parallelism there is the concern of the data base engine processing the query itself.</p>
<p>LINQ (<a href="http://msdn.microsoft.com/en-us/library/bb397919.aspx" target="_blank">LINQ to Objects</a> in particular) works by implementing a series of extension methods, most of which work on <a href="http://msdn.microsoft.com/en-us/library/19e6zeyy.aspx" target="_blank">IEnumerable&lt;T&gt;</a>.&#160; The language enhancements use these extension methods to create a very concise, readable alternative to using traditional <a href="http://msdn.microsoft.com/en-us/library/ttw7t8t6(VS.80).aspx" target="_blank">foreach</a> statement.&#160; For example, let’s revisit our <a href="http://reedcopsey.com/2010/01/22/parallelism-in-net-part-4-imperative-data-parallelism-aggregation/" target="_blank">minimum aggregation routine we wrote in Part 4</a>:</p>
<pre class="csharpcode"><span class="kwrd">double</span> min = <span class="kwrd">double</span>.MaxValue;
<span class="kwrd">foreach</span>(var item <span class="kwrd">in</span> collection)
{
    <span class="kwrd">double</span> <span class="kwrd">value</span> = item.PerformComputation();
    min = System.Math.Min(min, <span class="kwrd">value</span>);
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Here, we’re doing a very simple computation, but writing this in an imperative style.&#160; This can be loosely translated to English as:</p>
<pre>Create a very large number, and save it in min
Loop through each item in the collection.
For every item:
    Perform some computation, and save the result
    If the computation is less than min, set min to the computation </pre>
<p>Although this is fairly easy to follow, it’s quite a few lines of code, and it requires us to read through the code, step by step, line by line, in order to understand the intention of the developer.</p>
<p>We can rework this same statement, using LINQ:</p>
<pre class="csharpcode"><span class="kwrd">double</span> min = collection.Min(item =&gt; item.PerformComputation());</pre>
<p>Here, we’re after the same information.&#160; However, this is written using a declarative programming style.&#160; When we see this code, we’d naturally translate this to English as:</p>
<pre>Save the Min value of collection, determined via calling item.PerformComputation() </pre>
<p>That’s it – instead of multiple logical steps, we have one single, declarative <em>request</em>.&#160; This makes the developer’s intentions very clear, and very easy to follow.&#160; The system is free to implement this using whatever method required.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">Parallel LINQ (PLINQ)</a> extends LINQ to Objects to support parallel operations.&#160; This is a perfect fit in many cases when you have a problem that can be <a href="http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/" target="_blank">decomposed by data</a>.&#160; To show this, let’s again refer to our <a href="http://reedcopsey.com/2010/01/22/parallelism-in-net-part-4-imperative-data-parallelism-aggregation/" target="_blank">minimum aggregation routine from Part 4</a>, but this time, let’s review our final, parallelized version:</p>
<pre class="csharpcode"><span class="rem">// Safe, and fast!</span>
<span class="kwrd">double</span> min = <span class="kwrd">double</span>.MaxValue;
<span class="rem">// Make a &quot;lock&quot; object</span>
<span class="kwrd">object</span> syncObject = <span class="kwrd">new</span> <span class="kwrd">object</span>();
Parallel.ForEach(
    collection,
    <span class="rem">// First, we provide a local state initialization delegate.</span>
    () =&gt; <span class="kwrd">double</span>.MaxValue,
    <span class="rem">// Next, we supply the body, which takes the original item, loop state,</span>
    <span class="rem">// and local state, and returns a new local state</span>
    (item, loopState, localState) =&gt;
    {
        <span class="kwrd">double</span> <span class="kwrd">value</span> = item.PerformComputation();
        <span class="kwrd">return</span> System.Math.Min(localState, <span class="kwrd">value</span>);
    },
    <span class="rem">// Finally, we provide an Action&lt;TLocal&gt;, to &quot;merge&quot; results together</span>
    localState =&gt;
    {
        <span class="rem">// This requires locking, but it's only once per used thread</span>
        <span class="kwrd">lock</span>(syncObj)
            min = System.Math.Min(min, localState);
    }
);</pre>
<p>Here, we’re doing the same computation as above, but fully parallelized.&#160; Describing this in English becomes quite a feat: </p>
<pre>Create a very large number, and save it in min
Create a temporary object we can use for locking
Call Parallel.ForEach, specifying three delegates
    For the first delegate:
        Initialize a local variable to hold the local state to a very large number
    For the second delegate:
        For each item in the collection, perform some computation, save the result
        If the result is less than our local state, save the result in local state
    For the final delegate:
        Take a lock on our temporary object to protect our min variable
        Save the min of our min and local state variables</pre>
<p>Although this solves our problem, and does it in a very efficient way, we’ve created a set of code that is quite a bit more difficult to understand and maintain.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a> provides us with a very nice alternative.&#160; In order to use <a href="http://msdn.microsoft.com/en-us/library/dd460688(VS.100).aspx" target="_blank">PLINQ</a>, we need to learn one new extension method that works on <a href="http://msdn.microsoft.com/en-us/library/19e6zeyy.aspx" target="_blank">IEnumerable&lt;T&gt;</a> – <a href="http://msdn.microsoft.com/en-us/library/dd413602(VS.100).aspx" target="_blank">ParallelEnumerable.AsParallel()</a>.</p>
<p>That’s all we need to learn in order to use PLINQ<strong>: one single method</strong>.&#160; We can write our minimum aggregation in PLINQ very simply:</p>
<pre class="csharpcode"><span class="kwrd">double</span> min = collection.AsParallel().Min(item =&gt; item.PerformComputation());</pre>
<p>By simply adding “.AsParallel()” to our LINQ to Objects query, we converted this to using PLINQ and running this computation in parallel!&#160; </p>
<p>This can be loosely translated into English easily, as well:</p>
<pre>Process the collection in parallel
Get the Minimum value, determined by calling PerformComputation on each item </pre>
<p>Here, our intention is very clear and easy to understand.&#160; We just want to perform the same operation we did in serial, but run it “as parallel”.&#160; PLINQ completely extends LINQ to Objects: the entire functionality of LINQ to Objects is available.&#160; By simply adding a call to AsParallel(), we can specify that a collection should be processed in parallel.&#160; This is simple, safe, and incredibly useful.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/CP2k0Ee2wyI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/26/parallelism-in-net-part-6-declarative-data-parallelism/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/26/parallelism-in-net-part-6-declarative-data-parallelism/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 5, Partitioning of Work</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/Rs7BD6892ac/</link>
		<comments>http://reedcopsey.com/2010/01/26/parallelism-in-net-part-5-partitioning-of-work/#comments</comments>
		<pubDate>Tue, 26 Jan 2010 17:34:56 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/26/parallelism-in-net-part-5-partitioning-of-work/</guid>
		<description><![CDATA[When parallelizing any routine, we start by decomposing the problem.&#160; Once the problem is understood, we need to break our work into separate tasks, so each task can be run on a different processing element.&#160; This process is called partitioning.
Partitioning our tasks is a challenging feat.&#160; There are opposing forces at work here: too many [...]]]></description>
			<content:encoded><![CDATA[<p>When parallelizing any routine, we start by <a href="http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/" target="_blank">decomposing the problem</a>.&#160; Once the problem is understood, we need to break our work into separate tasks, so each task can be run on a different processing element.&#160; This process is called partitioning.</p>
<p>Partitioning our tasks is a challenging feat.&#160; There are opposing forces at work here: too many partitions adds overhead, too few partitions leaves processors idle.&#160; Trying to work the perfect balance between the two extremes is the goal for which we should aim.&#160; Luckily, the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> automatically handles much of this process.&#160; However, there are situations where the default partitioning may not be appropriate, and knowledge of our routines may allow us to guide the framework to making better decisions.</p>
<p> <span id="more-161"></span>
<p>First off, I’d like to say that this is a more advanced topic.&#160; It is perfectly acceptable to use the parallel constructs in the framework without considering the partitioning taking place.&#160; The default behavior in the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> is very well-behaved, even for unusual work loads, and should rarely be adjusted.&#160; I have found few situations where the default partitioning behavior in the TPL is not as good or better than my own hand-written partitioning routines, and recommend using the defaults unless there is a strong, measured, and profiled reason to avoid using them.&#160; However, understanding partitioning, and how the TPL partitions your data, helps in understanding the proper usage of the TPL.</p>
<p>I indirectly mentioned partitioning while discussing <a href="http://reedcopsey.com/2010/01/22/parallelism-in-net-part-4-imperative-data-parallelism-aggregation/" target="_blank">aggregation</a>.&#160; Typically, our systems will have a limited number of <em>Processing Elements (PE)</em>, which is the terminology used for hardware capable of processing a stream of instructions.&#160; For example, in a standard Intel i7 system, there are four processor cores, each of which has two potential hardware threads due to Hyperthreading.&#160; This gives us a total of 8 PEs – theoretically, we can have up to eight operations occurring concurrently within our system.</p>
<p>In order to fully exploit this power, we need to partition our work into <em>Tasks.</em>&#160; A task is a simple set of instructions that can be run on a PE.&#160; Ideally, we want to have at least one task per PE in the system, since fewer tasks means that some of our processing power will be sitting idle.&#160; A naive implementation would be to just take our data, and partition it with one element in our collection being treated as one task.&#160; When we loop through our collection in parallel, using this approach, we’d just process one item at a time, then reuse that thread to process the next, etc.&#160; There’s a flaw in this approach, however.&#160; It will tend to be slower than necessary, often slower than processing the data serially.</p>
<p>The problem is that there is overhead associated with each task.&#160; When we take a simple foreach loop body and implement it using the TPL, we add overhead.&#160; First, we change the body from a simple statement to a delegate, which must be invoked.&#160; In order to invoke the delegate on a separate thread, the delegate gets added to the <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx" target="_blank">ThreadPool</a>’s current work queue, and the ThreadPool must pull this off the queue, assign it to a free thread, then execute it.&#160; If our collection had one million elements, the overhead of trying to spawn one million tasks would destroy our performance.</p>
<p>The answer, here, is to partition our collection into groups, and have each group of elements treated as a single <em>task</em>.&#160; By adding a partitioning step, we can break our total work into small enough tasks to keep our processors busy, but large enough tasks to avoid overburdening the ThreadPool.&#160; There are two clear, opposing goals here:</p>
<p><strong>Always try to keep each processor working, but also try to keep the individual partitions as large as possible.</strong></p>
<p>When using <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.for(VS.100).aspx" target="_blank">Parallel.For</a>, the partitioning is always handled automatically.&#160; At first, partitioning here seems simple.&#160; A naive implementation would merely split the total element count up by the number of PEs in the system, and assign a chunk of data to each processor.&#160; Many hand-written partitioning schemes work in this exactly manner.&#160; This perfectly balanced, static partitioning scheme works very well if the amount of work is constant for each element.&#160; However, this is rarely the case.&#160; Often, the length of time required to process an element grows as we progress through the collection, especially if we’re doing numerical computations.&#160; In this case, the first PEs will finish early, and sit idle waiting on the last chunks to finish.&#160; Sometimes, work can decrease as we progress, since previous computations may be used to speed up later computations.&#160; In this situation, the first chunks will be working far longer than the last chunks.&#160; In order to balance the workload, many implementations create many small chunks, and reuse threads.&#160; This adds overhead, but does provide better load balancing, which in turn improves performance.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> handles this more elaborately.&#160; Chunks are determined at runtime, and start small.&#160; They grow slowly over time, getting larger and larger.&#160; This tends to lead to a near optimum load balancing, even in odd cases such as increasing or decreasing workloads.&#160; </p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd991870(VS.100).aspx" target="_blank">Parallel.ForEach</a> is a bit more complicated, however. When working with a generic <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a>, the number of items required for processing is not known in advance, and must be discovered at runtime.&#160; In addition, since we don’t have direct access to each element, the scheduler must enumerate the collection to process it.&#160; Since <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a> is not thread safe, it must lock on elements as it enumerates, create temporary collections for each chunk to process, and schedule this out.&#160; By default, it uses a partitioning method similar to the one described above.&#160; We can see this directly by looking at the <strong>Visual Partitioning</strong> sample shipped by the Task Parallel Library team, and available as part of the <a href="http://code.msdn.microsoft.com/ParExtSamples" target="_blank">Samples for Parallel Programming</a>.&#160; When we run the sample, with four cores and the default, Load Balancing partitioning scheme, we see this:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/01/foreach_paritioning.png"><img style="border-bottom: 0px; border-left: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px" title="foreach_paritioning" border="0" alt="foreach_paritioning" src="http://reedcopsey.com/blog/wp-content/uploads/2010/01/foreach_paritioning_thumb.png" width="500" height="633" /></a> </p>
<p>The colored bands represent each processing core.&#160; You can see that, when we started (at the top), we begin with very small bands of color.&#160; As the routine progresses through the <a href="http://msdn.microsoft.com/en-us/library/dd991870(VS.100).aspx" target="_blank">Parallel.ForEach</a>, the chunks get larger and larger (seen by larger and larger stripes).</p>
<p>Most of the time, this is fantastic behavior, and most likely will out perform any custom written partitioning.&#160; However, if your routine is not scaling well, it may be due to a failure in the default partitioning to handle your specific case.&#160; With prior knowledge about your work, it may be possible to partition data more meaningfully than the default Partitioner.</p>
<p>There is the option to use an <a href="http://msdn.microsoft.com/en-us/library/dd783404(VS.100).aspx" target="_blank">overload of Parallel.ForEach</a> which takes a <a href="http://msdn.microsoft.com/en-us/library/dd381768(VS.100).aspx" target="_blank">Partitioner&lt;T&gt;</a> instance.&#160; The <a href="http://msdn.microsoft.com/en-us/library/dd381768(VS.100).aspx" target="_blank">Partitioner&lt;T&gt;</a> class is an abstract class which allows for both static and dynamic partitioning.&#160; By overriding <a href="http://msdn.microsoft.com/en-us/library/dd381743(VS.100).aspx" target="_blank">Partitioner&lt;T&gt;.SupportsDynamicPartitions</a>, you can specify whether a dynamic approach is available.&#160; If not, your custom Partitioner&lt;T&gt; subclass would override <a href="http://msdn.microsoft.com/en-us/library/dd381767(VS.100).aspx" target="_blank">GetPartitions(int)</a>, which returns a list of IEnumerator&lt;T&gt; instances.&#160; These are then used by the Parallel class to split work up amongst processors.&#160; When dynamic partitioning is available, <a href="http://msdn.microsoft.com/en-us/library/dd381959(VS.100).aspx" target="_blank">GetDynamicPartitions()</a> is used, which returns an IEnumerable&lt;T&gt; for each partition.&#160; If you do decide to implement your own Partitioner&lt;T&gt;, keep in mind the goals and tradeoffs of different partitioning strategies, and design appropriately.</p>
<p>The <a href="http://code.msdn.microsoft.com/ParExtSamples" target="_blank">Samples for Parallel Programming</a> project includes a ChunkPartitioner class in the <strong>ParallelExtensionsExtras</strong> project.&#160; This provides example code for implementing your own, custom allocation strategies, including a static allocator of a given chunk size.&#160; Although implementing your own Partitioner&lt;T&gt; is possible, as I mentioned above, this is rarely required or useful in practice.&#160; The default behavior of the TPL is very good, often better than any hand written partitioning strategy.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/Rs7BD6892ac" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/26/parallelism-in-net-part-5-partitioning-of-work/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/26/parallelism-in-net-part-5-partitioning-of-work/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 4, Imperative Data Parallelism: Aggregation</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/8tLt-ebIRjE/</link>
		<comments>http://reedcopsey.com/2010/01/22/parallelism-in-net-part-4-imperative-data-parallelism-aggregation/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 01:14:19 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/22/parallelism-in-net-part-4-imperative-data-parallelism-aggregation/</guid>
		<description><![CDATA[In the article on simple data parallelism, I described how to perform an operation on an entire collection of elements in parallel.&#160; Often, this is not adequate, as the parallel operation is going to be performing some form of aggregation.
Simple examples of this might include taking the sum of the results of processing a function [...]]]></description>
			<content:encoded><![CDATA[<p>In the article on <a href="http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/" target="_blank">simple data parallelism</a>, I described how to perform an operation on an entire collection of elements in parallel.&#160; Often, this is not adequate, as the parallel operation is going to be performing some form of <a href="http://en.wikipedia.org/wiki/Aggregate_function" target="_blank">aggregation</a>.</p>
<p>Simple examples of this might include taking the sum of the results of processing a function on each element in the collection, or finding the minimum of the collection given some criteria.&#160; This can be done using the techniques described in <a href="http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/" target="_blank">simple data parallelism</a>, however, special care needs to be taken into account to <a href="http://en.wikipedia.org/wiki/Synchronization_(computer_science)" target="_blank">synchronize the shared data appropriately</a>.&#160; The Task Parallel Library has tools to assist in this synchronization.</p>
<p> <span id="more-157"></span>
<p>The main issue with <a href="http://en.wikipedia.org/wiki/Aggregate_function" target="_blank">aggregation</a> when parallelizing a routine is that you need to handle <a href="http://en.wikipedia.org/wiki/Synchronization_(computer_science)" target="_blank">synchronization of data</a>.&#160; Since multiple threads will need to write to a shared portion of data.&#160; Suppose, for example, that we wanted to parallelize a simple loop that looked for the minimum value within a dataset:</p>
<pre class="csharpcode"><span class="kwrd">double</span> min = <span class="kwrd">double</span>.MaxValue;
<span class="kwrd">foreach</span>(var item <span class="kwrd">in</span> collection)
{
    <span class="kwrd">double</span> <span class="kwrd">value</span> = item.PerformComputation();
    min = System.Math.Min(min, <span class="kwrd">value</span>);
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This seems like a good candidate for parallelization, but there is a problem here.&#160; If we just wrap this into a call to <a href="http://msdn.microsoft.com/en-us/library/dd992001(VS.100).aspx" target="_blank">Parallel.ForEach</a>, we’ll introduce a <a href="http://en.wikipedia.org/wiki/Race_condition" target="_blank">critical race condition</a>, and get the wrong answer.&#160; Let’s look at what happens here:</p>
<pre class="csharpcode"><span class="rem">// Buggy code!  Do not use!</span>
<span class="kwrd">double</span> min = <span class="kwrd">double</span>.MaxValue;
Parallel.ForEach(collection, item =&gt;
{
    <span class="kwrd">double</span> <span class="kwrd">value</span> = item.PerformComputation();
    min = System.Math.Min(min, <span class="kwrd">value</span>);
});</pre>
<p>This code has a fatal flaw: <strong>min</strong> will be checked, then set, by multiple threads simultaneously.&#160; Two threads may perform the check at the same time, and set the wrong value for min.&#160; Say we get a value of 1 in thread 1, and a value of 2 in thread 2, and these two elements are the first two to run.&#160; If both hit the min check line at the same time, both will determine that min should change, to 1 and 2 respectively.&#160; If element 1 happens to set the variable first, then element 2 sets the min variable, we’ll detect a min value of 2 instead of 1.&#160; This can lead to wrong answers.</p>
<p>Unfortunately, fixing this, with the <a href="http://msdn.microsoft.com/en-us/library/dd992001(VS.100).aspx" target="_blank">Parallel.ForEach</a> call we’re using, would require adding locking.&#160; We would need to rewrite this like:</p>
<pre class="csharpcode"><span class="rem">// Safe, but slow</span>
<span class="kwrd">double</span> min = <span class="kwrd">double</span>.MaxValue;
<span class="rem">// Make a &quot;lock&quot; object</span>
<span class="kwrd">object</span> syncObject = <span class="kwrd">new</span> <span class="kwrd">object</span>();
Parallel.ForEach(collection, item =&gt;
{
    <span class="kwrd">double</span> <span class="kwrd">value</span> = item.PerformComputation();
    <span class="kwrd">lock</span>(syncObject)
        min = System.Math.Min(min, <span class="kwrd">value</span>);
});</pre>
<p>This will potentially add a huge amount of overhead to our calculation.&#160; Since we can potentially block while waiting on the lock for every single iteration, we will most likely slow this down to where it is actually quite a bit slower than our serial implementation.&#160; The problem is the lock statement – any time you use <em>lock(object), </em>you’re almost assuring reduced performance in a parallel situation.&#160; This leads to two observations I’ll make:</p>
<p><strong>When parallelizing a routine, try to avoid locks.</strong></p>
<p>That being said:</p>
<p><strong>Always add any and all required synchronization to avoid </strong><a href="http://en.wikipedia.org/wiki/Race_condition" target="_blank"><strong>race conditions</strong></a><strong>.</strong></p>
<p>These two observations tend to be opposing forces – we often need to synchronize our algorithms, but we also want to avoid the synchronization when possible.&#160; Looking at our routine, there is no way to directly avoid this lock, since each element is potentially being run on a separate thread, and this lock is necessary in order for our routine to function correctly every time.</p>
<p>However, this isn’t the only way to design this routine to implement this algorithm.&#160; Realize that, although our collection may have thousands or even millions of elements, we have a limited number of <em>Processing Elements (PE)</em>.&#160; Processing Element is the standard term for a hardware element which can process and execute instructions.&#160; This typically is a core in your processor, but many modern systems have <a href="http://en.wikipedia.org/wiki/Hyper-threading" target="_blank">multiple hardware execution threads per core</a>.&#160; The Task Parallel Library will not execute the work for each item in the collection as a separate work item. Instead, when Parallel.ForEach executes, it will partition the collection into larger “chunks” which get processed on different threads via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx" target="_blank">ThreadPool</a>.&#160; This helps reduce the threading overhead, and help the overall speed.&#160; In general, the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel(VS.100).aspx" target="_blank">Parallel class</a> will only use one thread per PE in the system.</p>
<p>Given the fact that there are typically fewer threads than work items, we can rethink our algorithm design.&#160; We can parallelize our algorithm more effectively by approaching it differently.&#160; Because the basic aggregation we are doing here (Min) is <a href="http://en.wikipedia.org/wiki/Commutative" target="_blank">communitive</a>, we do not need to perform this in a given order.&#160; We knew this to be true already – otherwise, we wouldn’t have been able to parallelize this routine in the first place.&#160; With this in mind, we can treat each thread’s work independently, allowing each thread to serially process many elements with no locking, then, after all the threads are complete, “merge” together the results.</p>
<p>This can be accomplished via a different set of overloads in the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel(VS.100).aspx" target="_blank">Parallel class</a>: <a href="http://msdn.microsoft.com/en-us/library/dd990270(VS.100).aspx" target="_blank">Parallel.ForEach&lt;TSource,TLocal&gt;</a>.&#160; The idea behind these overloads is to allow each thread to begin by initializing some local state (TLocal).&#160; The thread will then process an entire set of items in the source collection, providing that state to the delegate which processes an individual item.&#160; Finally, at the end, a separate delegate is run which allows you to handle merging that local state into your final results.</p>
<p>To rewriting our routine using <a href="http://msdn.microsoft.com/en-us/library/dd990270(VS.100).aspx" target="_blank">Parallel.ForEach&lt;TSource,TLocal&gt;</a>, we need to provide three delegates instead of one.&#160; The most basic version of this function is declared as:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> ParallelLoopResult ForEach&lt;TSource, TLocal&gt;(
    IEnumerable&lt;TSource&gt; source,
    Func&lt;TLocal&gt; localInit,
    Func&lt;TSource, ParallelLoopState, TLocal, TLocal&gt; body,
    Action&lt;TLocal&gt; localFinally
)</pre>
<p>The first delegate (the <em>localInit</em> argument) is defined as Func&lt;TLocal&gt;.&#160; This delegate initializes our local state.&#160; It should return some object we can use to track the results of a <strong>single thread’s operations</strong>.</p>
<p>The second delegate (the <em>body </em>argument) is where our main processing occurs, although now, instead of being an Action&lt;T&gt;, we actually provide a Func&lt;TSource, ParallelLoopState, TLocal, TLocal&gt; delegate.&#160; This delegate will receive three arguments: our original element from the collection (TSource), a <a href="http://reedcopsey.com/2010/01/22/parallelism-in-net-part-3-imperative-data-parallelism-early-termination/" target="_blank">ParallelLoopState which we can use for early termination</a>, and the instance of our local state we created (TLocal).&#160; It should do whatever processing you wish to occur per element, then <strong>return the value of the local state </strong>after processing is completed.</p>
<p>The third delegate (the <em>localFinally</em> argument) is defined as Action&lt;TLocal&gt;.&#160; This delegate is passed our local state after it’s been processed by all of the elements this thread will handle.&#160; This is where you can merge your final results together.&#160; This may require synchronization, but now, instead of synchronizing once per element (potentially millions of times), you’ll only have to synchronize <em>once per thread</em>, which is an ideal situation.</p>
<p>Now that I’ve explained <em>how </em>this works, lets look at the code:</p>
<pre class="csharpcode"><span class="rem">// Safe, and fast!</span>
<span class="kwrd">double</span> min = <span class="kwrd">double</span>.MaxValue;
<span class="rem">// Make a &quot;lock&quot; object</span>
<span class="kwrd">object</span> syncObject = <span class="kwrd">new</span> <span class="kwrd">object</span>();
Parallel.ForEach(
    collection,
    <span class="rem">// First, we provide a local state initialization delegate.</span>
    () =&gt; <span class="kwrd">double</span>.MaxValue,
    <span class="rem">// Next, we supply the body, which takes the original item, loop state,</span>
    <span class="rem">// and local state, and returns a new local state</span>
    (item, loopState, localState) =&gt;
    {
        <span class="kwrd">double</span> <span class="kwrd">value</span> = item.PerformComputation();
        <span class="kwrd">return</span> System.Math.Min(localState, <span class="kwrd">value</span>);
    },
    <span class="rem">// Finally, we provide an Action&lt;TLocal&gt;, to &quot;merge&quot; results together</span>
    localState =&gt;
    {
        <span class="rem">// This requires locking, but it's only once per used thread</span>
        <span class="kwrd">lock</span>(syncObj)
            min = System.Math.Min(min, localState);
    }
);</pre>
<p>Although this is a bit more complicated than the previous version, it is now both thread-safe, and has minimal locking.&#160; </p>
<p>This same approach can be used by Parallel.For, although now, it’s <a href="http://msdn.microsoft.com/en-us/library/dd783299(VS.100).aspx" target="_blank">Parallel.For&lt;TLocal&gt;</a>.&#160; When working with <a href="threadsafe" target="_blank">Parallel.For&lt;TLocal&gt;</a>, you use the same triplet of delegates, with the same purpose and results.</p>
<p>Also, many times, you can completely avoid locking by using a method of the <a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx" target="_blank">Interlocked</a> class to perform the final aggregation in an atomic operation.&#160; The <a href="http://msdn.microsoft.com/en-us/library/dd460703(VS.100).aspx" target="_blank">MSDN example demonstrating this same technique using Parallel.For</a> uses the Interlocked class instead of a lock, since they are doing a sum operation on a long variable, which is possible via <a href="http://msdn.microsoft.com/en-us/library/x629ff68.aspx" target="_blank">Interlocked.Add</a>.</p>
<p>By taking advantage of local state, we can use the Parallel class methods to parallelize algorithms such as <a href="http://en.wikipedia.org/wiki/Aggregate_function" target="_blank">aggregation</a>, which, at first, may seem like poor candidates for parallelization.&#160; Doing so requires careful consideration, and often requires a slight redesign of the algorithm, but the performance gains can be significant if handled in a way to avoid excessive synchronization.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/8tLt-ebIRjE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/22/parallelism-in-net-part-4-imperative-data-parallelism-aggregation/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/22/parallelism-in-net-part-4-imperative-data-parallelism-aggregation/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 3, Imperative Data Parallelism: Early Termination</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/XJ4pR7AqZOc/</link>
		<comments>http://reedcopsey.com/2010/01/22/parallelism-in-net-part-3-imperative-data-parallelism-early-termination/#comments</comments>
		<pubDate>Fri, 22 Jan 2010 19:08:37 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/22/parallelism-in-net-part-3-imperative-data-parallelism-early-termination/</guid>
		<description><![CDATA[Although simple data parallelism allows us to easily parallelize many of our iteration statements, there are cases that it does not handle well.&#160; In my previous discussion, I focused on data parallelism with no shared state, and where every element is being processed exactly the same.
Unfortunately, there are many common cases where this does not [...]]]></description>
			<content:encoded><![CDATA[<p>Although <a href="http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/" target="_blank">simple data parallelism</a> allows us to easily parallelize many of our <a href="http://msdn.microsoft.com/en-us/library/32dbftby.aspx" target="_blank">iteration statements</a>, there are cases that it does not handle well.&#160; In my previous discussion, I focused on data parallelism with no shared state, and where every element is being processed exactly the same.</p>
<p>Unfortunately, there are many common cases where this does not happen.&#160; If we are dealing with a loop that requires <a href="http://msdn.microsoft.com/en-us/library/adbctzc4.aspx" target="_blank">early termination</a>, extra care is required when parallelizing.</p>
<p> <span id="more-156"></span>
<p>Often, while processing in a loop, once a certain condition is met, it is no longer necessary to continue processing.&#160; This may be a matter of finding a specific element within the collection, or reaching some error case.&#160; The important distinction here is that, it is often impossible to know until runtime, what set of elements needs to be processed.</p>
<p>In my <a href="http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/" target="_blank">initial discussion of data parallelism</a>, I mentioned that this technique is a candidate when you can <a href="http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/" target="_blank">decompose</a> the problem based on the data involved, and you wish to apply a single operation concurrently on all of the elements of a collection.&#160; This covers many of the potential cases, but sometimes, after processing some of the elements, we need to stop processing.</p>
<p>As an example, lets go back to our <a href="http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/" target="_blank">previous Parallel.ForEach example</a> with contacting a customer.&#160; However, this time, we’ll change the requirements slightly.&#160; In this case, we’ll add an extra condition – if the store is unable to email the customer, we will exit gracefully.&#160; The thinking here, of course, is that if the store is currently unable to email, the next time this operation runs, it will handle the same situation, so we can just skip our processing entirely.&#160; The original, serial case, with this extra condition, might look something like the following:</p>
<pre class="csharpcode"><span class="kwrd">foreach</span>(var customer <span class="kwrd">in</span> customers)
{
    <span class="rem">// Run some process that takes some time...</span>
    DateTime lastContact = theStore.GetLastContact(customer);
    TimeSpan timeSinceContact = DateTime.Now - lastContact;

    <span class="rem">// If it's been more than two weeks, send an email, and update...</span>
    <span class="kwrd">if</span> (timeSinceContact.Days &gt; 14)
    {
         <span class="rem">// Exit gracefully if we fail to email, since this </span>
         <span class="rem">// entire process can be repeated later without issue.</span>
         <span class="kwrd">if</span> (theStore.EmailCustomer(customer) == <span class="kwrd">false</span>)
             <span class="kwrd">break</span>;
         customer.LastEmailContact = DateTime.Now;
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Here, we’re processing our loop, but at any point, if we fail to send our email successfully, we just abandon this process, and assume that it will get handled correctly the next time our routine is run.&#160; If we try to parallelize this using Parallel.ForEach, as we did previously, we’ll run into an error almost immediately: the <a href="http://msdn.microsoft.com/en-us/library/adbctzc4.aspx" target="_blank">break statement</a> we’re using is only valid when enclosed within an <a href="http://msdn.microsoft.com/en-us/library/32dbftby.aspx" target="_blank">iteration statement</a>, such as <a href="http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx" target="_blank">foreach</a>.&#160; When we switch to Parallel.ForEach, we’re no longer within an iteration statement – we’re a delegate running in a method.</p>
<p>This needs to be handled slightly differently when parallelized.&#160; Instead of using the <a href="http://msdn.microsoft.com/en-us/library/adbctzc4.aspx" target="_blank">break</a> statement, we need to utilize a new class in the Task Parallel Library: <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopstate(VS.100).aspx" target="_blank">ParallelLoopState</a>.&#160; The ParallelLoopState class is intended to allow concurrently running loop bodies a way to interact with each other, and provides us with a way to break out of a loop.&#160; In order to use this, we will use a different overload of <a href="http://msdn.microsoft.com/en-us/library/dd992198(VS.100).aspx" target="_blank">Parallel.ForEach</a> which takes an IEnumerable&lt;T&gt; and an Action&lt;T, ParallelLoopState&gt; instead of an Action&lt;T&gt;.&#160; Using this, we can parallelize the above operation by doing:</p>
<pre class="csharpcode">Parallel.ForEach(customers, (customer, parallelLoopState) =&gt;
{
    <span class="rem">// Run some process that takes some time...</span>
    DateTime lastContact = theStore.GetLastContact(customer);
    TimeSpan timeSinceContact = DateTime.Now - lastContact;

    <span class="rem">// If it's been more than two weeks, send an email, and update...</span>
    <span class="kwrd">if</span> (timeSinceContact.Days &gt; 14)
    {
         <span class="rem">// Exit gracefully if we fail to email, since this </span>
         <span class="rem">// entire process can be repeated later without issue.</span>
         <span class="kwrd">if</span> (theStore.EmailCustomer(customer) == <span class="kwrd">false</span>)
             parallelLoopState.Break();
         <span class="kwrd">else</span>
             customer.LastEmailContact = DateTime.Now;
    }
});</pre>
<p>There are a couple of important points here.&#160; First, we didn’t actually instantiate the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopstate_members(VS.100).aspx" target="_blank">ParallelLoopState</a> instance.&#160; It was provided directly to us via the Parallel class.&#160; All we needed to do was change our <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" target="_blank">lambda expression</a> to reflect that we want to use the loop state, and the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel(VS.100).aspx" target="_blank">Parallel class</a> creates an instance for our use.&#160; We also needed to change our logic slightly when we call Break().&#160; Since Break() doesn’t stop the program flow within our block, we needed to add an else case to only set the property in customer when we succeeded.&#160; This <a href="http://msdn.microsoft.com/en-us/library/dd460721(VS.100).aspx" target="_blank">same technique can be used to break out of a Parallel.For loop</a>.</p>
<p>That being said, there is a huge difference between using ParallelLoopState to cause early termination and to use break in a standard iteration statement.&#160; When dealing with a loop serially, <a href="http://msdn.microsoft.com/en-us/library/adbctzc4.aspx" target="_blank">break</a> will immediately terminate the processing within the closest enclosing loop statement.&#160; Calling ParallelLoopState.Break(), however, has a very different behavior.</p>
<p>The issue is that, now, we’re no longer processing one element at a time.&#160; If we break in one of our threads, there are other threads that will likely still be executing.&#160; This leads to an important observation about termination of parallel code:</p>
<p><strong>Early termination in parallel routines is not immediate.&#160; Code will continue to run after you request a termination.</strong></p>
<p>This may seem problematic at first, but it is something you just need to keep in mind while designing your routine.&#160; <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopstate.break(VS.100).aspx" target="_blank">ParallelLoopState.Break()</a> should be thought of as a request.&#160; We are telling the runtime that no elements that were in the collection past the element we’re currently processing need to be processed, and leaving it up to the runtime to decide how to handle this as gracefully as possible.&#160; Although this may seem problematic at first, it is a good thing.&#160; If the runtime tried to immediately stop processing, many of our elements would be partially processed.&#160; It would be like putting a return statement in a random location throughout our loop body – which could have horrific consequences to our code’s maintainability.</p>
<p>In order to understand and effectively write parallel routines, we, as developers, need a subtle, but profound shift in our thinking.&#160; We can no longer think in terms of sequential processes, but rather need to think in terms of requests to the system that may be handled differently than we’d first expect.&#160; This is more natural to developers who have dealt with asynchronous models previously, but is an important distinction when moving to concurrent programming models.</p>
<p>As an example, I’ll discuss the Break() method.&#160; <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopstate.break(VS.100).aspx" target="_blank">ParallelLoopState.Break()</a> functions in a way that may be unexpected at first.&#160; When you call <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopstate.break(VS.100).aspx" target="_blank">Break()</a> from a loop body, the runtime will continue to process <em>all elements of the collection that were found prior to the element that was being processed when the Break() method was called</em>.&#160; This is done to keep the behavior of the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopstate.break(VS.100).aspx" target="_blank">Break()</a> method as close to the behavior of the <a href="http://msdn.microsoft.com/en-us/library/adbctzc4.aspx" target="_blank">break</a> statement as possible. We can see the behavior in this simple code:</p>
<pre class="csharpcode">var collection = Enumerable.Range(0, 20);
var pResult = Parallel.ForEach(collection, (element, state) =&gt;
{
    <span class="kwrd">if</span> (element &gt; 10)
    {
        Console.WriteLine(<span class="str">&quot;Breaking on {0}&quot;</span>, element);
        state.Break();
    }
    Console.WriteLine(element);
});</pre>
<p>If we run this, we get a result that may seem unexpected at first:</p>
<pre>0
2
1
5
6
3
4
10
Breaking on 11
11
Breaking on 12
12
9
Breaking on 13
13
7
8
Breaking on 15
15</pre>
<p>What is occurring here is that we loop until we find the first element where the element is greater than 10.&#160; In this case, this was found, the first time, when one of our threads reached element 11.&#160; It requested that the loop stop by calling <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopstate.break(VS.100).aspx" target="_blank">Break()</a> at this point.&#160; However, the loop continued processing until all of the elements less than 11 were completed, then terminated.&#160; This means that it will guarantee that elements 9, 7, and 8 are completed before it stops processing.&#160; You can see our other threads that were running each tried to break as well, but since Break() was called on the element with a value of 11, it decides which elements (0-10) must be processed.</p>
<p>If this behavior is not desirable, there is another option.&#160; Instead of calling <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopstate.break(VS.100).aspx" target="_blank">ParallelLoopState.Break()</a>, you can call <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopstate.stop(VS.100).aspx" target="_blank">ParallelLoopState.Stop()</a>.&#160; The Stop() method requests that the runtime terminate as soon as possible , without guaranteeing that any other elements are processed.&#160; Stop() will not stop the processing within an element, so elements already being processed will continue to be processed.&#160; It will prevent new elements, even ones found earlier in the collection, from being processed.&#160; Also, when Stop() is called, the ParallelLoopState’s <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallelloopstate.isstopped(VS.100).aspx" target="_blank">IsStopped</a> property will return true.&#160; This lets longer running processes poll for this value, and return after performing any necessary cleanup.</p>
<p>The basic rule of thumb for choosing between Break() and Stop() is the following.</p>
<ul>
<li>Use ParallelLoopState.Stop() when possible, since it terminates more quickly.&#160; This is particularly useful in situations where you are searching for an element or a condition in the collection.&#160; Once you’ve found it, you do not need to do any other processing, so Stop() is more appropriate. </li>
<li>Use ParallelLoopState.Break() if you need to more closely match the behavior of the C# break statement. </li>
</ul>
<p>Both methods behave differently than our C# break statement.&#160; Unfortunately, when parallelizing a routine, more thought and care needs to be put into every aspect of your routine than you may otherwise expect.&#160; This is due to my second observation: </p>
<p><strong>Parallelizing a routine will almost always change its behavior.</strong></p>
<p>This sounds crazy at first, but it’s a concept that’s so simple its easy to forget.&#160; We’re purposely telling the system to process more than one thing at the same time, which means that the sequence in which things get processed is no longer deterministic.&#160; It is easy to change the behavior of your routine in very subtle ways by introducing parallelism.&#160; Often, the changes are not avoidable, even if they don’t have any adverse side effects.&#160; This leads to my final observation for this post:</p>
<p><strong>Parallelization is something that should be handled with care and forethought, added by design, and not just introduced casually.</strong></p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/XJ4pR7AqZOc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/22/parallelism-in-net-part-3-imperative-data-parallelism-early-termination/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/22/parallelism-in-net-part-3-imperative-data-parallelism-early-termination/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 2, Simple Imperative Data Parallelism</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/W0AJuqgB4Q0/</link>
		<comments>http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/#comments</comments>
		<pubDate>Thu, 21 Jan 2010 01:15:46 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/</guid>
		<description><![CDATA[In my discussion of Decomposition of the problem space, I mentioned that Data Decomposition is often the simplest abstraction to use when trying to parallelize a routine.&#160; If a problem can be decomposed based off the data, we will often want to use what MSDN refers to as Data Parallelism as our strategy for implementing [...]]]></description>
			<content:encoded><![CDATA[<p>In my discussion of <a href="http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/">Decomposition</a> of the problem space, I mentioned that Data Decomposition is often the simplest abstraction to use when trying to parallelize a routine.&#160; If a problem can be decomposed based off the data, we will often want to use what MSDN refers to as <a href="http://msdn.microsoft.com/en-us/library/dd537608(VS.100).aspx">Data Parallelism</a> as our strategy for implementing our routine.&#160; The Task Parallel Library in .NET 4 makes implementing Data Parallelism, for most cases, very simple.</p>
<p> <span id="more-155"></span>
<p>Data Parallelism is the main technique we use to parallelize a routine which can be decomposed based off data.&#160; Data Parallelism refers to taking a single collection of data, and having a single operation be performed concurrently on elements in the collection.&#160; </p>
<p>One side note here: Data Parallelism is also sometimes referred to as the <em>Loop Parallelism Pattern</em> or <em>Loop-level Parallelism.&#160; </em>In general, for this series, I will try to use the terminology used in the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx">MSDN Documentation for the Task Parallel Library</a>.&#160; This should make it easier to investigate these topics in more detail.</p>
<p>Once we’ve determined we have a problem that, potentially, can be decomposed based on data, implementation using Data Parallelism in the TPL is quite simple.&#160; Let’s take our example from the <a href="http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/">Data Decomposition discussion</a> – a simple contrast stretching filter.&#160; Here, we have a collection of data (pixels), and we need to run a simple operation on each element of the pixel.&#160; Once we know the minimum and maximum values, we most likely would have some simple code like the following:</p>
<pre class="csharpcode"><span class="kwrd">for</span> (<span class="kwrd">int</span> row=0; row &lt; pixelData.GetUpperBound(0); ++row)
{
    <span class="kwrd">for</span> (<span class="kwrd">int</span> col=0; col &lt; pixelData.GetUpperBound(1); ++col)
    {
        pixelData[row, col] = AdjustContrast(pixelData[row, col], minPixel, maxPixel);
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This simple routine loops through a two dimensional array of pixelData, and calls the AdjustContrast routine on each pixel.</p>
<p>As I mentioned, when you’re <a href="http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/" target="_blank">decomposing a problem space</a>, most <a href="http://msdn.microsoft.com/en-us/library/32dbftby.aspx" target="_blank">iteration statements</a> are potentially candidates for data decomposition.&#160; Here, we’re using two for loops – one looping through rows in the image, and a second nested loop iterating through the columns.&#160; We then perform one, independent operation on each element based on those loop positions.</p>
<p>This is a prime candidate – we have no shared data, no dependencies on anything but the pixel which we want to change.&#160; Since we’re using a for loop, we can easily parallelize this using the <a href="http://msdn.microsoft.com/en-us/library/dd783539(VS.100).aspx" target="_blank">Parallel.For</a> method in the TPL:</p>
<pre class="csharpcode">Parallel.For(0, pixelData.GetUpperBound(0), row =&gt;
{
    <span class="kwrd">for</span> (<span class="kwrd">int</span> col=0; col &lt; pixelData.GetUpperBound(1); ++col)
    {
        pixelData[row, col] = AdjustContrast(pixelData[row, col], minPixel, maxPixel);
    }
});</pre>
<p>Here, by simply changing our first for loop to a call to <a href="http://msdn.microsoft.com/en-us/library/dd783539(VS.100).aspx" target="_blank">Parallel.For</a>, we can parallelize this portion of our routine.&#160; Parallel.For works, as do many methods in the TPL, by creating a <a href="http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx" target="_blank">delegate</a> and using it as an argument to a method.&#160; In this case, our for loop iteration block becomes a delegate creating via a <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" target="_blank">lambda expression</a>.&#160; This lets you write code that, superficially, looks similar to the familiar for loop, but functions quite differently at runtime.</p>
<p>We could easily do this to our second for loop as well, but that may not be a good idea.&#160; There is a balance to be struck when writing parallel code.&#160; We want to have enough work items to keep all of our processors busy, but the more we partition our data, the more overhead we introduce.&#160; In this case, we have an image of data – most likely hundreds of pixels in both dimensions.&#160; By just parallelizing our first loop, each row of pixels can be run as a single task.&#160; With hundreds of rows of data, we are providing fine enough granularity to keep all of our processors busy.</p>
<p>If we parallelize both loops, we’re potentially creating millions of independent tasks.&#160; This introduces extra overhead with no extra gain, and will actually reduce our overall performance.&#160; This leads to my first guideline when writing parallel code:</p>
<p><strong>Partition your problem into enough tasks to keep each processor busy throughout the operation, but not more than necessary to keep each processor busy.</strong></p>
<p>Also note that I parallelized the outer loop.&#160; I could have just as easily partitioned the inner loop.&#160; However, partitioning the inner loop would have led to many more discrete work items, each with a smaller amount of work (operate on one pixel instead of one row of pixels).&#160; My second guideline when writing parallel code reflects this:</p>
<p><strong>Partition your problem in a way to place the most work possible into each task.</strong></p>
<p>This typically means, in practice, that you will want to parallelize the routine at the “highest” point possible in the routine, typically the outermost loop.&#160; If you’re looking at parallelizing methods which call other methods, you’ll want to try to partition your work high up in the stack – as you get into lower level methods, the performance impact of parallelizing your routines may not overcome the overhead introduced.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd783539(VS.100).aspx" target="_blank">Parallel.For</a> works great for situations where we know the number of elements we’re going to process in advance.&#160; If we’re iterating through an <a href="http://msdn.microsoft.com/en-us/library/5y536ey6.aspx" target="_blank">IList&lt;T&gt;</a> or an array, this is a typical approach.&#160; However, there are other <a href="http://msdn.microsoft.com/en-us/library/32dbftby.aspx" target="_blank">iteration statements</a> common in C#.&#160; In many situations, we’ll use <a href="http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx" target="_blank">foreach</a> instead of a for loop.&#160; This can be more understandable and easier to read, but also has the advantage of working with collections which only implement <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx" target="_blank">IEnumerable&lt;T&gt;</a>, where we do not know the number of elements involved in advance.</p>
<p>As an example, lets take the following situation.&#160; Say we have a collection of Customers, and we want to iterate through each customer, check some information about the customer, and if a certain case is met, send an email to the customer and update our instance to reflect this change.&#160; Normally, this might look something like:</p>
<pre class="csharpcode"><span class="kwrd">foreach</span>(var customer <span class="kwrd">in</span> customers)
{
    <span class="rem">// Run some process that takes some time...</span>
    DateTime lastContact = theStore.GetLastContact(customer);
    TimeSpan timeSinceContact = DateTime.Now - lastContact;

    <span class="rem">// If it's been more than two weeks, send an email, and update...</span>
    <span class="kwrd">if</span> (timeSinceContact.Days &gt; 14)
    {
       theStore.EmailCustomer(customer);
       customer.LastEmailContact = DateTime.Now;
    }
}</pre>
<p>Here, we’re doing a fair amount of work for each customer in our collection, but we don’t know how many customers exist.&#160; If we assume that theStore.GetLastContact(customer) and theStore.EmailCustomer(customer) are both side-effect free, thread safe operations, we could parallelize this using <a href="http://msdn.microsoft.com/en-us/library/dd992001(VS.100).aspx" target="_blank">Parallel.ForEach</a>:</p>
<pre class="csharpcode">Parallel.ForEach(customers, customer =&gt;
{
    <span class="rem">// Run some process that takes some time...</span>
    DateTime lastContact = theStore.GetLastContact(customer);
    TimeSpan timeSinceContact = DateTime.Now - lastContact;

    <span class="rem">// If it's been more than two weeks, send an email, and update...</span>
    <span class="kwrd">if</span> (timeSinceContact.Days &gt; 14)
    {
       theStore.EmailCustomer(customer);
       customer.LastEmailContact = DateTime.Now;
    }
});</pre>
<p>Just like Parallel.For, we rework our loop into a method call accepting a delegate created via a <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" target="_blank">lambda expression</a>.&#160; This keeps our new code very similar to our original iteration statement, however, this will now execute in parallel.&#160; The same guidelines apply with Parallel.ForEach as with Parallel.For.</p>
<p>The other iteration statements, <a href="http://msdn.microsoft.com/en-us/library/370s1zax.aspx" target="_blank">do</a> and <a href="http://msdn.microsoft.com/en-us/library/2aeyhxcd.aspx" target="_blank">while</a>, do not have direct equivalents in the Task Parallel Library.&#160; These, however, are very easy to <a href="http://blogs.msdn.com/pfxteam/archive/2009/08/12/9867246.aspx" target="_blank">implement using Parallel.ForEach</a> and the <a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx" target="_blank">yield keyword</a>.</p>
<p>Most applications can benefit from implementing some form of <a href="http://msdn.microsoft.com/en-us/library/dd537608(VS.100).aspx" target="_blank">Data Parallelism</a>.&#160; Iterating through collections and performing “work” is a very common pattern in nearly every application.&#160; When the problem can be decomposed by data, we often can parallelize the workload by merely changing foreach statements to Parallel.ForEach method calls, and for loops to Parallel.For method calls.&#160; Any time your program operates on a collection, and does a set of work on each item in the collection where that work is not dependent on other information, you very likely have an opportunity to parallelize your routine.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/W0AJuqgB4Q0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/20/parallelism-in-net-part-2-simple-imperative-data-parallelism/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 1, Decomposition</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/HBCYP1axEro/</link>
		<comments>http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 23:50:21 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/</guid>
		<description><![CDATA[The first step in designing any parallelized system is Decomposition.&#160; Decomposition is nothing more than taking a problem space and breaking it into discrete parts.&#160; When we want to work in parallel, we need to have at least two separate things that we are trying to run.&#160; We do this by taking our problem and [...]]]></description>
			<content:encoded><![CDATA[<p>The first step in designing any parallelized system is <a href="http://en.wikipedia.org/wiki/Decomposition_(computer_science)"><strong>Decomposition</strong></a>.&#160; Decomposition is nothing more than taking a problem space and breaking it into discrete parts.&#160; When we want to work in parallel, we need to have at least two separate things that we are trying to run.&#160; We do this by taking our problem and decomposing it into parts.</p>
<p>There are two common abstractions that are useful when discussing parallel decomposition: <strong>Data Decomposition </strong>and <strong>Task Decomposition</strong>.&#160; These two abstractions allow us to think about our problem in a way that helps leads us to correct decision making in terms of the algorithms we’ll use to parallelize our routine.</p>
<p> <span id="more-154"></span>
<p>To start, I will make a couple of minor points.</p>
<ul>
<li>I’d like to stress that Decomposition has nothing to do with specific algorithms or techniques.&#160; It’s about how you approach and think about the problem, not how you solve the problem using a specific tool, technique, or library.&#160; Decomposing the problem is about constructing the appropriate mental model: once this is done, you can choose the appropriate design and tools, which is a subject for future posts.</li>
<li>Decomposition, being unrelated to tools or specific techniques, is not specific to .NET in any way.&#160; This should be the first step to parallelizing a problem, and is valid using any framework, language, or toolset.&#160; However, this gives us a starting point – without a proper understanding of decomposition, it is difficult to understand the proper usage of specific classes and tools within the .NET framework.</li>
</ul>
<p><strong>Data Decomposition </strong>is often the simpler abstraction to use when trying to parallelize a routine.&#160; In order to decompose our problem domain by data, we take our entire set of data and break it into smaller, discrete portions, or chunks.&#160; We then work on each chunk in the data set in parallel.</p>
<p>This is particularly useful if we can process each element of data independently of the rest of the data.&#160; In a situation like this, there are some wonderfully simple techniques we can use to take advantage of our data.&#160; By decomposing our domain by data, we can very simply parallelize our routines.&#160; In general, we, as developers, should be always searching for data that can be decomposed.</p>
<p>Finding data to decompose if fairly simple, in many instances.&#160; Data decomposition is typically used with collections of data.&#160; Any time you have a collection of items, and you’re going to perform work on or with each of the items, you potentially have a situation where parallelism can be exploited.&#160; This is fairly easy to do in practice: look for <a href="http://msdn.microsoft.com/en-us/library/32dbftby.aspx">iteration statements</a> in your code, such as <a href="http://msdn.microsoft.com/en-us/library/ch45axte.aspx">for</a> and <a href="http://msdn.microsoft.com/en-us/library/ttw7t8t6.aspx">foreach</a>.</p>
<p>Granted, every for loop is not a candidate to be parallelized.&#160; If the collection is being modified as it’s iterated, or the processing of elements depends on other elements, the iteration block may need to be processed in serial.&#160; However, if this is not the case, data decomposition may be possible.</p>
<p>Let’s look at one example of how we might use data decomposition.&#160; Suppose we were working with an image, and we were applying a simple <a href="http://www.ph.tn.tudelft.nl/Courses/FIP/noframes/fip-istogram.html">contrast stretching filter</a>.&#160; When we go to apply the filter, once we know the minimum and maximum values, we can apply this to each pixel independently of the other pixels.&#160; This means that we can easily decompose this problem based off <em>data</em> – we will do the same operation, in parallel, on individual chunks of data (each pixel).</p>
<p><strong>Task Decomposition</strong>, on the other hand, is focused on the individual tasks that need to be performed instead of focusing on the data.&#160; In order to decompose our problem domain by tasks, we need to think about our algorithm in terms of discrete operations, or tasks, which can then later be parallelized.</p>
<p>Task decomposition, in practice, can be a bit more tricky than data decomposition.&#160; Here, we need to look at what our algorithm actually does, and how it performs its actions.&#160; Once we have all of the basic steps taken into account, we can try to analyze them and determine whether there are any constraints in terms of shared data or ordering.&#160; There are no simple things to look for in terms of finding tasks we can decompose for parallelism; every algorithm is unique in terms of its tasks, so every algorithm will have unique opportunities for task decomposition.</p>
<p>For example, say we want our software to perform some customized actions on startup, prior to showing our main screen.&#160; Perhaps we want to check for proper licensing, notify the user if the license is not valid, and also check for updates to the program.&#160; Once we verify the license, and that there are no updates, we’ll start normally.&#160; In this case, we can decompose this problem into <em>tasks </em>– we have a few tasks, but there are at least two discrete, independent tasks (check licensing, check for updates) which we can perform in parallel.&#160; Once those are completed, we will continue on with our other tasks.</p>
<p>One final note – Data Decomposition and Task Decomposition are not mutually exclusive.&#160; Often, you’ll mix the two approaches while trying to parallelize a single routine.&#160; It’s possible to decompose your problem based off data, then further decompose the processing of each element of data based on tasks.&#160; </p>
<p>This just provides a framework for thinking about our algorithms, and for discussing the problem.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/HBCYP1axEro" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/19/parallelism-in-net-part-1-decomposition/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Introduction</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/1D16YFQzO5Q/</link>
		<comments>http://reedcopsey.com/2010/01/19/parallelism-in-net-introduction/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 20:50:24 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Parallelism]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/19/parallelism-in-net-introduction/</guid>
		<description><![CDATA[Parallel programming is something that every professional developer should understand, but is rarely discussed or taught in detail in a formal manner.&#160; Software users are no longer content with applications that lock up the user interface regularly, or take large amounts of time to process data unnecessarily.&#160; Modern development requires the use of parallelism.&#160; There [...]]]></description>
			<content:encoded><![CDATA[<p>Parallel programming is something that every professional developer should understand, but is rarely discussed or taught in detail in a formal manner.&#160; Software users are no longer content with applications that lock up the user interface regularly, or take large amounts of time to process data unnecessarily.&#160; Modern development requires the use of parallelism.&#160; There is no longer any excuses for us as developers.</p>
<p>Learning to write parallel software is challenging.&#160; It requires more than reading that one chapter on parallelism in our programming language book of choice…</p>
<p> <span id="more-153"></span>
<p>Today’s systems are no longer getting faster with each generation; in many cases, newer computers are actually slower than previous generation systems.&#160; Modern hardware is shifting towards conservation of power, with processing scalability coming from having multiple computer cores, not faster and faster CPUs.&#160; Our CPU frequencies no longer double on a regular basis, but <a href="http://en.wikipedia.org/wiki/Moores_law">Moore’s Law</a> is still holding strong.&#160; Now, however, instead of scaling transistors in order to make processors faster, hardware manufacturers are scaling the transistors in order to add more discrete hardware processing threads to the system.</p>
<p>This changes how we should think about software.&#160; In order to take advantage of modern systems, we need to <a href="http://en.wikipedia.org/wiki/Moores_law#Parallelism_and_Moore.27s_law">redesign and rewrite our algorithms to work in parallel</a>.&#160; As with any design domain, it helps tremendously to have a common language, as well as a common set of patterns and tools.</p>
<p>For .NET developers, this is an exciting time for parallel programming.&#160; Version 4 of the .NET Framework is adding the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx">Task Parallel Library</a>.&#160; This has been back-ported to .NET 3.5sp1 as part of the <a href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx">Reactive Extensions for .NET</a>, and is available for use today in both .NET 3.5 and .NET 4.0 beta.</p>
<p>In order to fully utilize the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx">Task Parallel Library</a> and parallelism, both in .NET 4 and previous versions, we need to understand the proper terminology.&#160; For this series, I will provide an introduction to some of the basic concepts in parallelism, and relate them to the tools available in .NET.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/1D16YFQzO5Q" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/19/parallelism-in-net-introduction/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/19/parallelism-in-net-introduction/</feedburner:origLink></item>
		<item>
		<title>Better User and Developer Experiences – From Windows Forms to WPF with MVVM</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/XZ5_Rf57vIg/</link>
		<comments>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 22:24:37 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm/</guid>
		<description><![CDATA[This series introduces the Model-View-ViewModel Pattern from the point of view of a Windows Forms developer. The goal is not to introduce WPF, but to demonstrate some of the new features within Windows Presentation Foundation, and show how they should force every WPF developer to re-think how they design their applications.   The Model-View-ViewModel [...]]]></description>
			<content:encoded><![CDATA[<p>This series introduces the Model-View-ViewModel Pattern from the point of view of a Windows Forms developer. The goal is not to introduce WPF, but to demonstrate some of the new features within Windows Presentation Foundation, and show how they should force every WPF developer to re-think how they design their applications.   <br />The Model-View-ViewModel pattern is introduced after a discussion of three of the main features in WPF which enable it&#8217;s usage. In order to illustrate this, three versions a single application were written:</p>
<ul>
<li>A Windows Forms application </li>
<li>A WPF Version of the application, using the same style </li>
<li>A WPF Version of the application, built using MVVM </li>
</ul>
<p>This allows a detailed understanding of the reasons behind MVVM, as well as the technology that enables the pattern.</p>
<p> <span id="more-150"></span>
<p>The series is written in multiple parts:</p>
<ul>
<li><a href="http://reedcopsey.com/2009/11/20/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-introduction/">Introduction</a></li>
<li><a href="http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/">The Model</a></li>
<li><a href="http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-2-our-application-in-windows-forms/">Our Application In Windows Forms</a></li>
<li><a href="http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/">Our Application In WPF</a></li>
<li><a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">Data Binding</a></li>
<li><a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">Commands</a></li>
<li><a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">Templating</a></li>
<li><a href="http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/">MVVM</a></li>
<li><a href="http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/">Conclusion</a></li>
</ul>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/XZ5_Rf57vIg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm/</feedburner:origLink></item>
		<item>
		<title>Better User and Developer Experiences – From Windows Forms to WPF with MVVM: Conclusion</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/0IYWL3yMQlI/</link>
		<comments>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 22:16:40 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/</guid>
		<description><![CDATA[Windows Presentation Foundation provides us with new opportunities to build applications that are very flexible to design, easy to maintain, and clear to understand.&#160; By taking advantage of Data Binding, Commands, and Templating, we can rethink the way we build our applications, and design them using the Model-View-ViewModel Pattern.
Now that I’ve walked through how we [...]]]></description>
			<content:encoded><![CDATA[<p>Windows Presentation Foundation provides us with new opportunities to build applications that are very flexible to design, easy to maintain, and clear to understand.&#160; By taking advantage of <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">Data Binding</a>, <a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">Commands</a>, and <a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">Templating</a>, we can rethink the way we build our applications, and design them using the <a href="http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/">Model-View-ViewModel Pattern</a>.</p>
<p>Now that I’ve walked through how we do this, I will revisit our original RSS Feed Reader application, and show samples of how this changes the design and code in this simple application.</p>
<p> <span id="more-148"></span>
<p>First, lets look at our Model.</p>
<p>Our Model classes, as expected, remained completely unchanged through all three versions of our software.&#160; The same Model was usable by the Windows Forms application, our WPF application, and our WPF with MVVM version of our application.&#160; This works because our Model described nothing but it’s own, domain specific information.&#160; It took no dependencies on a presentation technology, and made no assumptions of how it would be used.</p>
<p>Next, lets begin by looking at our View.</p>
<p>In <a href="http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/">Part 7</a>, I mentioned that we should keep a goal in mind for the View: <strong>The user interface should be declared entirely in XAML, with zero code behind.&#160; </strong>Unfortunately, it’s impossible to have absolutely zero code, but we’ve managed to move our entire declaration of both our Window and our UserControl into XAML, so all that is left in the code is the constructor which calls InitializeComponent:</p>
<pre class="csharpcode"><span class="kwrd">namespace</span> RssMVVM.Views
{
    <span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> MainView
    {
        <span class="kwrd">public</span> MainView()
        {
            InitializeComponent();
        }
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
</p>
<p>In this example, we’ve succeeded in accomplishing our goal – we have no code in the code behind other than the automatically generated code that is required to initialize our UserControl or WIndow.</p>
<p>Our XAML changed, as well.&#160; Instead of having nearly every element named in order to make them accessible via code, we now use data binding to bind directly to their values.&#160; For example, in our original WPF version of our UserControl, the first set of TextBox elements was written like this:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;0&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;textBoxTitle&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;textBoxLink&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;2&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">x:Name</span><span class="kwrd">=&quot;textBoxDescription&quot;</span> <span class="kwrd">/&gt;</span></pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Now, in our MVVM version, we change this to:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;0&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span>
  <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Title, Mode=OneWay}&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span>
  <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Link, Mode=OneWay, Converter={StaticResource StringToUriConverter}}&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;2&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span>
  <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Description, Mode=OneWay}&quot;</span><span class="kwrd">/&gt;</span></pre>
<p>At first glance, this may seem like extra work.&#160; However, the second eliminates all of the code required to set and manage changes in the first (two entire methods).&#160; The MVVM version also has a subtle, yet profound advantage over the first: the XAML code is exactly describing what will exist inside that text box.&#160; This provides a level of self-documentation in your XAML, which fits in perfectly with it’s declarative nature.&#160; In the original version, the only clue we would have to the TextBox’s purpose is the name we specified.</p>
<p>I will mention – I had to “cheat” here, to some extent.&#160; There is one issue that was not easily resolved in porting this application to MVVM: the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.aspx">WebBrowser control</a>.&#160; Unfortunately, the WebBrowser control wraps a COM component, and is not a native WPF control.&#160; I suspect that this led to an unfortunately design decision: <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.webbrowser.source.aspx">WebBrowser.Source</a> is not a standard WPF DependencyProperty, and as a result, can not be used with Data Binding like standard control elements.</p>
<p>There are at least two options for handling this situation.&#160; We could have easily handled this by using code in the code behind file.&#160; This would be a minor deviation from our goal, but as the goal of no code in code behind is a guideline, not a hard fixed rule, it would be a valid option.&#160; However, there is another feature in WPF we can use in many situations such as this: <a href="http://msdn.microsoft.com/en-us/library/ms749011.aspx">Attached Properties</a>.&#160; In my case, I prefer to use attached properties, since this creates a tool that is easily reusable on any WebBrowser control.&#160; By using an attached property, we can create a BindableSource property that allows us to use Data Binding with a WebBrowser, just by changing the XAML to:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">WebBrowser</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;2&quot;</span> <span class="attr">RssMVVM:WebBrowserUtility</span>.<span class="attr">BindableSource</span><span class="kwrd">=&quot;{Binding Uri}&quot;</span> <span class="kwrd">/&gt;</span></pre>
<p>The final change I introduced was the addition of a DataTemplate in the application’s XAML: </p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Application.Resources</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">DataTemplate</span> <span class="attr">DataType</span><span class="kwrd">=&quot;{x:Type ViewModels:FeedViewModel}&quot;</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">Views:FeedControl</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">DataTemplate</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Application.Resources</span><span class="kwrd">&gt;</span></pre>
<p>This simple addition allows <a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">WPF’s templating</a> to automatically construct and manage our View for the UserControl, saving us all of the code required to construct and place the control.</p>
<p>We made our clean View possible by introducing two ViewModel classes: <strong>MainViewModel</strong> and <strong>FeedViewModel</strong>.&#160; Looking at our ViewModel classes, we see their simplicity.&#160; Most of the code involved in our ViewModel class is nothing but a wrapper around our Model in order to allow it to properly implement <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx">INotifyPropertyChanged</a>, and to handle the creation of our <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx">ICommand</a> implementations.</p>
<p>The nice thing here, is we can see all of our logic, everything that the View is going to use, in one location.&#160; There is nothing tied to a specific View here, so it is easy to generate unit tests for our ViewModel classes.&#160; All of our logic is wrapped into a commands, and the rest of our ViewModel classes do nothing but wrap properties to properly handle INotifyPropertyChanged.</p>
<p>I purposely did not make custom styles for the WPF versions of this application.&#160; That would be very easy to do, and potentially could make the WPF versions of this application much better looking and more usable.&#160; Though it would be a fun and easy exercise, the main goal of this series is to demonstrate how the code itself can be changed in order to make maintaining and redesigning the application simple – not how to make a beautiful designed user interface.</p>
<p>The Visual Studio Solution used in this article, with full source code, is available on <a href="http://code.msdn.microsoft.com/WinFormToWPFMVVM">MSDN Code Gallery</a>.&#160; I encourage you to download and compare all three versions of the RSS Feed Reader application in detail.&#160; The progression of this application, and the advantages it brings, will be much more noticeable when looking at the full source code.</p>
<p>Windows Presentation Foundation has a lot to offer every application developer.&#160; By taking advantage of its unique features, we can build our applications in a way that is maintainable, testable, designable, and simple to implement.&#160; The Model-View-ViewModel design pattern provides a clean pattern we can use improve our efficiency as developers.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/0IYWL3yMQlI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/</feedburner:origLink></item>
		<item>
		<title>Better User and Developer Experiences – From Windows Forms to WPF with MVVM: Part 7, MVVM</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/2-u_vx4RcoM/</link>
		<comments>http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 01:40:11 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/</guid>
		<description><![CDATA[I mentioned in the introduction that a new architectural pattern has emerged for Windows Presentation Foundation: Model-View-ViewModel.&#160; As I mentioned, MVVM can make developing applications in WPF efficient, quick, and highly maintainable.&#160; Now that I’ve covered some of the basic technological advances in WPF, mainly Data Binding, Commands, and Templating, it’s time to bring everything [...]]]></description>
			<content:encoded><![CDATA[<p>I mentioned in the <a href="http://reedcopsey.com/2009/11/20/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-introduction/">introduction</a> that a new <a href="http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)">architectural pattern</a> has emerged for Windows Presentation Foundation: <a href="http://en.wikipedia.org/wiki/MVVM">Model-View-ViewModel</a>.&#160; As I mentioned, MVVM can make developing applications in WPF efficient, quick, and highly maintainable.&#160; Now that I’ve covered some of the basic technological advances in WPF, mainly <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">Data Binding</a>, <a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">Commands</a>, and <a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">Templating</a>, it’s time to bring everything together, and demonstrate how this improves our jobs as developers.</p>
<p> <span id="more-145"></span>
<p>As I mentioned in the section on templating, WPF’s design strives to maintain a clear separation between presentation and logic.&#160; We’ve seen some of the advantages in terms of control creation – unlike Windows Forms, we can completely change the way a control looks merely by creating a new template, using XAML in a completely declarative form.&#160; No code is required.&#160; We get more flexibility with less work.&#160; By separating presentation and logic, WPF creates opportunities for much greater degrees of flexibility in our applications.</p>
<p>As a developer, I see this as a very “good thing”.&#160; The Model-View-ViewModel pattern has one goal – to extend this same flexibility into our applications by creating <em>and maintaining</em> a clean <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a> through our entire application.</p>
<p>In order to understand MVVM, I will start off by defining our distinct <a href="http://en.wikipedia.org/wiki/Concern_(computer_science)">concerns</a>, the individual “parts” of our application.&#160; </p>
<p>I already defined our arguably most important concern: <a href="http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/">the Model</a>.&#160; Again, the Model is the domain-specific data and logic used within your application.&#160; It’s the goal – the “data” you’re working to expose to your users.&#160; This may be customer records in a database, or product information on a website, or anything else.&#160; In our case, it’s two classes, the <strong>Feed</strong> and the <strong>FeedItem</strong> class.&#160; In Model-View-ViewModel, our goal is to keep the model unaware of the specific application or technology that’s using it.&#160; The Model knows about itself, and nothing else.</p>
<p>The second concern I’ll discuss is the View.&#160; The View is the entire user interface of your application – it’s everything the user’s interact with directly: every control, every button, every check box, every window.&#160; As I <a href="http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/">mentioned in part 3</a>, WPF changes how the View is normally defined.&#160; Instead of developing the user interface via code, we use XAML to create an XML-based, declarative description of the interface.</p>
<p>Let’s review our goal of maintaining a full separation of presentation and logic, this time just in terms of the View.&#160; When we create our user interface, we want to define what the user will see (presentation) without worrying about how the program works (logic).&#160; XAML is perfect for this, as it lets us design the user interface with zero code involved.&#160; This gives us an easy way to think about our View<strong> </strong>in terms of our goal: <strong>The user interface should be declared entirely in XAML, with zero code behind.</strong></p>
<p>Succeeding in this goal has many advantages.&#160; It makes the View very flexible – a designer can take our View and stylize it or change it in any way desired, without changing or effecting a single line of code.&#160; Also, if there is no logic in the View itself, it eliminates the risk of “stale” or unused code creeping into the View, which often happens in Windows Forms.</p>
<p>Now that we have the View and the Model defined, we need a way to hook the two things together.&#160; Something has to coordinate our actions between the Model and the View, so that the user’s interaction has an effect on the Model.&#160; This is handled by our third concern: the ViewModel.</p>
<p>The ViewModel serves the purpose of adapting the Model to be <strong>directly usable by the View</strong>.&#160; In order to do this, we take advantage of <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">WPF’s incredible Data Binding support</a>.&#160; In MVVM, the ViewModel sits between the View and the Model, and basically acts similar to an <a href="http://en.wikipedia.org/wiki/Adapter_pattern">Adapter</a> – it translates the properties and methods of the Model to a form that can be directly used via Data Binding.</p>
<p>The ViewModel also provides us a place to manage application state and logic.&#160; By taking advantage of <a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">WPF’s Commanding Infrastructure</a>, we can define ICommand instances in the ViewModel that the View can directly access via Data Binding.&#160; This provides us a clean way to keep the logic out of the View – again, the View works completely via Data Binding to the ViewModel.&#160; This provides a means by which we can hook into logic from the View without having the logic be tied to the specific view that is using it.</p>
<p>Here is a diagram illustrating our three areas of concern:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/01/MVVM.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="MVVM" border="0" alt="MVVM" src="http://reedcopsey.com/blog/wp-content/uploads/2010/01/MVVM_thumb.png" width="404" height="739" /></a>There are some important aspects of this diagram I will discuss, for each of our Concerns, some critical points</p>
<ul>
<li>The Model
<ul>
<li>The Model is unaware of anything except itself </li>
<li>The Model could be used by any form of program, and is not tied to a specific framework or technology </li>
</ul>
</li>
<li>The View
<ul>
<li>The View is defined entirely in XAML </li>
<li>The View only needs to know what to bind to, by name.&#160; It does not need to know anything about what will happen when properties change or commands are executed. </li>
<li>The View’s state is completely based upon data binding </li>
</ul>
</li>
<li>The ViewModel
<ul>
<li>The ViewModel knows nothing about the View </li>
<li>The ViewModel directly interacts with the Model, in order to expose it for data binding </li>
<li>The ViewModel manages the Application-specific information </li>
</ul>
</li>
</ul>
<p>The advantages here are profound:</p>
<p>Our Model, since it is self contained, can be used in any way we wish.&#160; If, later, we decided we needed a web-based API to the same model, we could use the Model unchanged.&#160; If the successor to WPF comes along, and we need to update our application to use it, the Model remains unchanged.</p>
</p>
<p>Our View, since it has no logic, is completely designable.&#160; The View can be modified by a designer with little or no programming experience, with no fear of breaking the logic.&#160; The only knowledge that the designer needs to know is what properties and commands are available, and their names – everything else is handled directly by the framework to make it work.&#160; This leads to a tremendous amount of flexibility in the View – the entire look and feel of an application can be changed at any time.</p>
<p>Our ViewModel gets a nice advantage from this architecture, as well.&#160; Since it is not tied to a specific View, it is very easily testable.&#160; The logic of our application is all exposed through self-contained ICommand implementations, which are easy to test.&#160; The data is exposed via properties; again, easy to test.</p>
<p>There is still one issue left to resolve, though.&#160; At this point, we know how to architect a single window or form correctly – the Model is used by the ViewModel, and the View “hooks” into the ViewModel with data binding.&#160; This works great for a single user control – but we still need to create and wire up the controls in the first place.</p>
<p>At first glance, it seems like we’d need to know about the View and the ViewModel in order to do this.&#160; For the ViewModel to be used as a binding source, it needs to be set as the DataContext of the correct View.&#160; We need a way, given a ViewModel, to construct a View and set its DataContext.&#160; In order to do this, we break one of our rules – the ViewModel, in order to construct the View, needs to know about the Views.</p>
<p>WPF, again, provides us with the final tool required for MVVM: <a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">Templating</a>.&#160; The same mechanism that our ListBox used when we discussed templating can be used for our ViewModel.&#160; Instead of trying to construct our View, we can setup a simple DataTemplate that specifies that our View is used to render our ViewModel.&#160; This will look similar to:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">DataTemplate</span> <span class="attr">DataType</span><span class="kwrd">=&quot;{x:Type local:OurViewModel}&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">local:OurView</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">DataTemplate</span><span class="kwrd">&gt;</span></pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This DataTemplate tells WPF that, any time we say to directly render an instance of <strong>OurViewModel</strong>, it should construct an instance of <strong>OurView</strong>, place it at that location, and set the DataContext of the OurView instance to the instance of OurViewModel.&#160; Basically, WPF will do all of the work for us, just be specifying a DataTemplate.</p>
<p>Since DataTemplates are definable in XAML, and will propagate downwards through the Visual Tree in WPF, this lets our View automatically set itself up.&#160; All that needs to happen is to provide a ContentPresenter in our View which binds, using standard DataBinding, to a ViewModel, and WPF will do all of the plumbing for us!</p>
<p>WPF adds three profound features: <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">Data Binding</a>, <a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">Commands</a>, and <a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">Templates</a>.&#160; By using these three feature sets appropriately, we can redesign the architecture of our applications by using the Model-View-ViewModel pattern. This maintains a clear separation of concerns, allows for easy changes and redesign of the View, provides good testability, and keeps our domain specific classes completely isolated.</p>
<p><a href="http://reedcopsey.com/2010/01/07/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-conclusion/">… Continued in the Conclusion …</a></p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/2-u_vx4RcoM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/</feedburner:origLink></item>
		<item>
		<title>Better User and Developer Experiences – From Windows Forms to WPF with MVVM: Part 6, Templating</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/9ck-s_K-XXw/</link>
		<comments>http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 01:02:33 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/</guid>
		<description><![CDATA[In order to rethink how we architect and write client applications, there is one last important concept Windows Presentation Foundation introduces, beyond the excellent Data Binding and Commanding support I’ve already discussed.&#160; WPF adds an entire suite of features specifically related to Styling and Templating.&#160; This is often discussed in relation to improving the overall [...]]]></description>
			<content:encoded><![CDATA[<p>In order to rethink how we architect and write client applications, there is one last important concept <a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx">Windows Presentation Foundation</a> introduces, beyond the excellent <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">Data Binding</a> and <a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">Commanding</a> support I’ve already discussed.&#160; WPF adds an entire suite of features specifically related to <a href="http://msdn.microsoft.com/en-us/library/ms745683.aspx">Styling and Templating</a>.&#160; This is often discussed in relation to improving the overall look, feel, and usability of applications written using WPF – the key to the new user experience (UX) WPF allows.&#160; However, the templating engine introduced with WPF has other side effects, which change the way we should design our software, not just change the way we stylize our software.</p>
<p> <span id="more-136"></span>
<p>Windows Presentation Foundation, in its design, strives to keep a clear separation of presentation and logic.&#160; This is apparent throughout <a href="http://msdn.microsoft.com/en-us/library/ms750441.aspx">its architecture</a>, but perhaps most notable in one of the core building blocks of every WPF application: the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.control.aspx">Control class</a>.&#160; </p>
<p>Controls, in WPF, have two completely separate parts.&#160; There is the logical portion, and then there is a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.controltemplate.aspx">ControlTemplate</a> that defines how the control is represented visually; how the control looks.&#160; The difference in thinking, even in this core element, is apparent from the documentation.</p>
<p>Here is how the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.aspx">Control class in Windows Forms</a> is described in MSDN:</p>
<blockquote><p>Defines the base class for controls, which are components with visual representation.</p></blockquote>
<p>Compare that to the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.control.aspx">Control class in WPF</a>:</p>
<blockquote><p>Represents the base class for user interface (UI) elements that use a ControlTemplate to define their appearance.</p></blockquote>
<p>Note the difference here.&#160; Even the most basic definition of a “Control”, the core component used to build applications, has changed in Windows Presentation Foundation.&#160; In Windows Forms, when you defined a control, you defined everything about the control directly.&#160; Take a button – a button not only had to deal with the fact that it has behavior (its something visual on which you click, which in turn triggers behavior) – it also directly handled its own rendering.&#160; Typically, if you wanted to make a <em>Button </em>that looked dramatically different from the standard button, you’d make a custom control (ie: a separate class), where you’d handle, not only the button’s behavior, but also all of the code required to paint the customized button.&#160; In WPF, making custom controls is much less common – instead of making a separate class for the new button, you could just make a custom <a href="http://msdn.microsoft.com/en-us/library/ms745683.aspx#styling_controltemplates">Style, a ControlTemplate</a> which completely changes the way the button is rendered.&#160; However, the behavior of the button is the same, since it’s still uses the standard “Button” class.</p>
<p>This is the key to making WPF applications highly designable – it’s very easy to allow a designer to go in and completely customize the look and feel of every part of your application <strong>without introducing custom controls</strong>.&#160; Many people tout this as WPF’s advantage over Windows Forms, as well as nearly every other preceding UI technology.</p>
<p>In our case, however, we’re interested in how to architect our application from a code standpoint, not how to make it pretty.&#160; The styling and templating engine in WPF provides another very critical component: the <a href="http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.aspx">DataTemplate</a>.</p>
<p>Data templates are most often used by WPF controls whose purpose is to display a collection of items.&#160; These typically are the classes that derive from <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.aspx">ItemsControl</a>, such as <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.listbox.aspx">ListBox</a> and <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.treeview.aspx">TreeView</a>.&#160; For our purposes, lets look at ListBox.</p>
<p>In Windows Forms, when you had a ListBox, by default it just displayed a list of items as text.&#160; Changing this required <a href="http://msdn.microsoft.com/en-us/library/ms229679.aspx">creating an owner drawn list box</a>, which was a challenge, even for a simple change in style.&#160; This requires handling your own GDI+ drawing using the Graphics class, and pushed everything into code that is difficult to write and maintain.</p>
<p>In WPF, this is handled by a <a href="http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.aspx">DataTemplate</a>.&#160; By default, you can bind a collection of any objects to a ListBox, and the ListBox will list the results of calling <a href="http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx">Object.ToString()</a> on each element of the collection.&#160; Custom drawing is handled very easily by using a DataTemplate.&#160; In the <a href="http://msdn.microsoft.com/en-us/library/ms745683.aspx#styling_datatemplates">Styling and Templating example</a>, the DataTemplate creates a Border with a nested Image, bound to the Source property of each element.&#160; This causes the ListBox to display a list of Images.</p>
<p>In our RSS Feed Reader, we use the same technique to display a list of FeedItems.&#160; Our ListBox is bound directly to a list of our RssModel.FeedItem class, and without a DataTemplate, we see:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/01/ListNoTemplate.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="ListBox with No Template" border="0" alt="ListBox with No Template" src="http://reedcopsey.com/blog/wp-content/uploads/2010/01/ListNoTemplate_thumb.png" width="372" height="484" /></a> </p>
<p>However, in our UserControl, we added a very simple DataTemplate:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">DataTemplate</span> <span class="attr">DataType</span><span class="kwrd">=&quot;{x:Type model:FeedItem}&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">TextBlock</span> <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Title}&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">DataTemplate</span><span class="kwrd">&gt;</span></pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This causes our display to change.&#160; Now, instead of just listing the class name (the default behavior of ToString() on our RssModel.FeedItem class), we display a TextBlock containing the FeedItem’s Title property:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/01/ListWithTemplate.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="ListWithTemplate" border="0" alt="ListWithTemplate" src="http://reedcopsey.com/blog/wp-content/uploads/2010/01/ListWithTemplate_thumb.png" width="359" height="484" /></a> </p>
<p>This is much nicer, and very simple to implement.&#160; </p>
<p>DataTemplates, however, go far beyond just displaying Text – we could have displayed borders, images, text, or any other complex item we wished, merely by specifying a template in our UserControl.&#160; The idea behind a DataTemplate is that you specify, in XAML, how <strong>any object should be represented visually</strong>.&#160; This lets us tell the user interface to <strong>directly render a custom class</strong>, without the code needing to know or worry about the class being rendered properly.</p>
<p>In our case, we used that to customize the display of a list of FeedItems.&#160; The <a href="http://msdn.microsoft.com/en-us/library/ms745683.aspx#styling_datatemplates">MSDN sample</a> displayed a list of Photo classes using pictures surrounded by a border.&#160; This flexibility is the key to rethinking our architecture, and in our final installment, I’ll delve into how and why this should change the way you think about designing client applications.</p>
<p><a href="http://reedcopsey.com/2010/01/06/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-7-mvvm/">… Continued in Part 7, MVVM …</a></p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/9ck-s_K-XXw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/</feedburner:origLink></item>
		<item>
		<title>Better User and Developer Experiences – From Windows Forms to WPF with MVVM: Part 5, Commands</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/CH-IYXQFMCE/</link>
		<comments>http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/#comments</comments>
		<pubDate>Tue, 29 Dec 2009 01:40:12 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/</guid>
		<description><![CDATA[In the last article, I explained how Windows Presentation Foundation improves upon data handling via it’s excellent support for data binding.&#160; However, data is only part of the equation.&#160; In order to be a more effective framework, WPF also provides us a way to more effectively handle our application specific logic.
It does this by providing [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://reedcopsey.com/?p=104">last article</a>, I explained how Windows Presentation Foundation improves upon data handling via it’s excellent support for data binding.&#160; However, data is only part of the equation.&#160; In order to be a more effective framework, WPF also provides us a way to more effectively handle our application specific logic.</p>
<p>It does this by providing a unified model for separating the originator of an action from the effect produced by the action, via the <a href="http://msdn.microsoft.com/en-us/library/ms752308.aspx">Commanding</a> infrastructure.</p>
</p>
<p> <span id="more-122"></span>Commands in WPF are a very powerful abstraction.&#160; MSDN clearly states the goals of the commanding infrastructure:
</p>
<pre>What makes commands different from a simple event handler
attached to a button or a timer is that commands separate the
semantics and the originator of an action from its logic.
This allows for multiple and disparate sources to invoke the
same command logic, and it allows the command logic to be
customized for different targets.</pre>
<p>This follows a simple, but pervasive goal in WPF – separation of logic from presentation.&#160; In the case of commands, the goal is to decouple an “action” from the object on which its working, as well as from the user interface element that triggers the action.</p>
<p>Also MSDN’s <a href="http://msdn.microsoft.com/en-us/library/ms752308.aspx">Commanding discussion</a> focuses on the <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx">RoutedCommand</a> implementations, for our purposes, we’ll use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx">ICommand interface</a> directly.&#160; ICommand is a simple interface, and it provides two functions:</p>
<ol>
<li>Provide a means (CanExecute method) to determine whether an action can be run in the current context, as well as a way to track when this changes (CanExecuteChanged event). </li>
<li>Provide a method (Execute) to perform a given action </li>
</ol>
<p>By providing this in a simple interface, we can make our own class which wraps this functionality into any series of delegates.&#160; In our case, we made an ICommand class called ActionCommand, which lets us do some nice things.</p>
<p>For example, in the DataContext we use for our specific feed information UserControl, we start off by defining an ICommand as a property:</p>
<pre class="csharpcode"><span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// Gets the open feed command.</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="rem">/// &lt;value&gt;The open feed command.&lt;/value&gt;</span>
<span class="kwrd">public</span> ICommand OpenFeedCommand
{
    get;
    <span class="kwrd">private</span> set;
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p><!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->We then initialize this directly using:</p>
<pre class="csharpcode"><span class="kwrd">this</span>.OpenFeedCommand = <span class="kwrd">new</span> ActionCommand(<span class="kwrd">this</span>.OpenFeed, () =&gt; <span class="kwrd">true</span>);</pre>
<p>Basically, this provides us a Property, directly on our DataContext, that lets us call an OpenFeed method.&#160; Also, since we can now directly expose the SelectedFeedItem due to Data Binding (as discussed in <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">part 4</a>), we simplify our logic as well.</p>
<p>Now, in our code, we can replace our event handler:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ButtonOpenLink_Click(<span class="kwrd">object</span> sender, RoutedEventArgs e)
{
    <span class="kwrd">if</span> (<span class="kwrd">this</span>.Feed != <span class="kwrd">null</span>)
    {
        FeedItem item = <span class="kwrd">this</span>.Feed.Items[<span class="kwrd">this</span>.listBoxFeeds.SelectedIndex];
        <span class="kwrd">if</span> (item != <span class="kwrd">null</span>)
        {
            System.Diagnostics.Process.Start(item.Link.AbsoluteUri);
        }
    }
}</pre>
<p>With a dramatically simplified OpenFeed method:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> OpenFeed()
{
    <span class="kwrd">if</span> (<span class="kwrd">this</span>.SelectedFeedItem != <span class="kwrd">null</span>)
    {
        System.Diagnostics.Process.Start(<span class="kwrd">this</span>.SelectedFeedItem.Link.AbsoluteUri);
    }
}</pre>
<p>Our XAML will change, so instead of using the event handler, we switch to specifying the Command for our button directly, using <a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">WPF’s DataBinding</a>:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Button</span>
   <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Height</span><span class="kwrd">=&quot;23&quot;</span>
   <span class="attr">HorizontalAlignment</span><span class="kwrd">=&quot;Right&quot;</span> <span class="attr">Margin</span><span class="kwrd">=&quot;0,0,0,0&quot;</span>
   <span class="attr">VerticalAlignment</span><span class="kwrd">=&quot;Top&quot;</span> <span class="attr">Width</span><span class="kwrd">=&quot;60&quot;</span>
   <span class="attr">Command</span><span class="kwrd">=&quot;{Binding OpenFeedCommand}&quot;</span><span class="kwrd">&gt;</span>
Open
<span class="kwrd">&lt;/</span><span class="html">Button</span><span class="kwrd">&gt;</span></pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p><!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->Note the differences here in approach – we’re accomplishing the same goal (hooking our code into the button being clicked by the user), but in a very different way. </p>
<p>In Windows Forms, and even in WPF when we use the event approach, we’re directly handling the button’s click event, and our logic gets mixed with the fact that we’re using a button in the interface.&#160; If we were to change from a button to a menu, or a hyperlink, or some other control, we’d have to change our code to handle the different type of event, and move our logic across.&#160; The code is always aware of what control is triggering some action.</p>
<p>Now, by using an ICommand, we’re doing something different.&#160; What we are accomplishing here is making two statements in our code:</p>
<ol>
<li>Our user should be able to call a command to Open a feed (OpenFeedCommand) </li>
<li>The OpenFeedCommand performs this function (launches the browser with the feed’s URI). </li>
</ol>
<p>Nothing in the code knows how this command will get invoked – it can be from a button’s click (as it is here), but it could just as easily be triggered by any <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommandsource.aspx">ICommandSource</a>, including a <a href="http://msdn.microsoft.com/en-us/library/system.windows.documents.hyperlink.aspx">Hyperlink</a>, <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.menuitem.aspx">MenuItem</a>, or even a <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.keygesture.aspx">KeyGesture</a>.</p>
<p>The important point here is that the code does not know, or care, what triggered it.&#160; We could rework the user interface to use completely different controls <strong>without changing one line of C# code</strong>, because we decoupled the action from what triggered the action by using a Command.</p>
<p><a href="http://reedcopsey.com/2010/01/04/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-6-templating/">… Continued in Part 6, Templating …</a></p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/CH-IYXQFMCE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/</feedburner:origLink></item>
		<item>
		<title>Better User and Developer Experiences – From Windows Forms to WPF with MVVM: Part 4, Data Binding</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/HDs2MGhbBF4/</link>
		<comments>http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/#comments</comments>
		<pubDate>Thu, 26 Nov 2009 01:56:00 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=104</guid>
		<description><![CDATA[Now that I’ve demonstrated how WPF can be written in the same manner, using the same methods as prior windowing frameworks, it’s time to explain why this is a bad idea.&#160; To do this effectively, I’m going to discuss a few things that WPF introduces, and explain how they should change the way all of [...]]]></description>
			<content:encoded><![CDATA[<p>Now that I’ve demonstrated how WPF can be written in the same manner, using the same methods as prior windowing frameworks, it’s time to explain why this is a bad idea.&#160; To do this effectively, I’m going to discuss a few things that WPF introduces, and explain how they should change the way all of us approach building user interfaces.&#160; One thing I do want to mention – this series is not meant to be a full tutorial on WPF, rather an explanation of how to use features in WPF effectively.</p>
<p>The first new concept in WPF I’ll introduce is the new, more powerful, more flexible model for <a href="http://msdn.microsoft.com/en-us/library/ms752347.aspx">Data Binding</a>.</p>
</p>
<p> <span id="more-104"></span>Windows Presentation Foundation provides an entirely new form of <a href="http://msdn.microsoft.com/en-us/library/ms752347.aspx">Data Binding</a> than previous data binding technologies.&#160; <a href="http://msdn.microsoft.com/en-us/library/ef2xyb33.aspx">Data Binding existed in Windows Forms</a>, but was limited to being bound to pretty specific <a href="http://msdn.microsoft.com/en-us/library/f3y6cb0c.aspx">data sources</a>.&#160; Many developers have used data bound controls prior to WPF, but the way data binding works in WPF has changed.&#160; The data binding support in WPF adds the potential to use completely different programming models than we used previously.
</p>
<p>So lets start with explaining data binding, in general terms.&#160; <a href="http://en.wikipedia.org/wiki/Data_binding">Data binding</a> is a general purpose technique that lets you take two (or potentially more than two) separate elements, and “bind” them together so that their values stay synchronized.&#160; Typically, a control in the user interface (like a text box or a label) is bound to a property on some object containing your business logic.</p>
<p>The advantages of this should be obvious pretty quickly, provided this works correctly.&#160; However, previous attempts at data binding have all fallen short when it came time to use them in practical, real-world problems.&#160; I believe this comes down to the inability of most data binding frameworks to handle everything required.&#160; For data binding to truly be effective, a binding framework should provide the following.</p>
<ul>
<li>An easy way to bind user interface elements to data sources </li>
<li>A clean way to specify a data source for an entire collection of objects </li>
<li>A consistent way to specify bindings, no matter what is being bound </li>
<li>Allow flexibility in what triggers updates </li>
<li>An effective means of validation of values </li>
<li>The means to do conversion of the data through the binding itself </li>
</ul>
<p>Most frameworks for data binding have provided some, but not all, of the features available above.&#160; I’m going to address the above bullet points, and show how WPF provides for clean data binding.&#160; We’ll start with the first three points:</p>
<ul>
<li>An easy way to bind user interface elements to data sources </li>
<li>A clean way to specify a data source for an entire collection of objects </li>
<li>A consistent way to specify bindings, no matter what is being bound </li>
</ul>
<p>Nearly all user interface items in WPF derive from <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.aspx">FrameworkElement</a>.&#160; Whenever you create a Window or a UserControl in WPF, you have the option of specifying <strong>any object</strong> as the Framework Element’s <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext.aspx">DataContext</a>.&#160; The DataContext property specifies “the data context for an element when it participates in data binding”.&#160; Whenever an object has a DataContext specified, you can use WPF’s data binding to bind directly to properties defined on that object.</p>
<p>There is a very important line in the documentation for <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext.aspx">DataContext</a>:</p>
<pre>This dependency property inherits property values. If there are child
elements without other values for DataContext established through local values
or styles, then the property system will set the value to be the DataContext
value of the nearest parent element with this value assigned.</pre>
<p>What this means is that you don’t have to specify the DataContext for every element in your Window or UserControl.&#160; You can specify the DataContext for a UserControl, and, by default, <strong>every control inside of the UserControl will automatically use that same DataContext for data binding</strong>!&#160; This is incredibly powerful.</p>
<p>For example, in both our <a href="http://reedcopsey.com/?p=100">Windows Forms</a> and <a href="http://reedcopsey.com/?p=103">WPF (version 1)</a> applications, we had a UserControl defined for displaying information about our Feed object.&#160; Whenever we’d update our Feed object, we would write a bunch of code triggered by setting our property to update our UI, such as:</p>
<pre class="csharpcode"><span class="rem">// .. Called when Feed changes to update the user interface</span>
    <span class="kwrd">this</span>.textBoxTitle.Text = <span class="kwrd">this</span>.Feed.Title;
    <span class="kwrd">this</span>.textBoxLink.Text = <span class="kwrd">this</span>.Feed.Link.AbsoluteUri;
    <span class="kwrd">this</span>.textBoxDescription.Text = <span class="kwrd">this</span>.Feed.Description;</pre>
<p>
  </p>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p><!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --></p>
<p>By using data binding, we can completely eliminate this code.&#160; Instead of doing this, we could, for example, just set the DataContext of our UserControl to the Feed object itself.&#160; Once we’ve done that, we can just specify, in our XAML (which can be done in the designer), which property in our DataContext which we want to bind to our individual TextBox controls:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;0&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Title, Mode=OneWay}&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Link.AbsoluteUri, Mode=OneWay}&quot;</span> <span class="kwrd">/&gt;</span>
<span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;2&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Text</span><span class="kwrd">=&quot;{Binding Path=Feed.Description, Mode=OneWay}&quot;</span><span class="kwrd">/&gt;</span></pre>
<p><!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --></p>
<p>Now, all of a sudden, we have full, up to date user interface controls, and we can completely eliminate two entire methods (<em>ResetFeed</em> and <em>ClearFeed</em>) from our code!&#160; Less code means less to maintain, less to test, and less to worry about.&#160; Our TextBox instances don’t have a DataContext specified, so they automatically inherit the DataContext of the UserControl (since that is the first parent element with a DataContext provided).&#160; They then bind directly to the property of the object in the DataContext.</p>
<p>This solves our first three bullet points – we can bind to <strong>any object </strong>(*see note below) using <strong>declarative syntax</strong> (in XAML), and we can <strong>specify the object one time</strong>, at a high level such as a Window or UserControl, via <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext.aspx">FrameworkElement.DataContext</a>.</p>
<p>Let’s move on to the next two points:</p>
<ul>
<li>Allow flexibility in what triggers updates </li>
<li>An effective means of validation of values </li>
</ul>
<p>Windows Presentation Foundation provides the means to handle this, as well.&#160; Again, with no changes to our code, we can declaratively add support for both of the above bullet points.</p>
<p>First, what triggers an <a href="http://msdn.microsoft.com/en-us/library/ms752347.aspx#what_triggers_source_updates">update to the binding can be specified</a>, in XAML, by providing an <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx">UpdateSourceTrigger</a>.&#160; This lets us say, explicitly, that we want the property to update every time we type a letter into a TextBox (by setting the trigger to “PropertyChanged”), or only when the control loses focus (“LostFocus”).&#160; In addition, <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger.aspx">UpdateSourceTrigger</a> lets us explicitly handle property updates, even though this is not as commonly used.</p>
<p>Validation can be handled, and again specified declaratively by using XAML, in multiple ways.&#160; I do not want to cover Validation here in detail, but it is <a href="http://msdn.microsoft.com/en-us/library/ms752347.aspx#data_validation">discussed in detail on MSDN</a>.&#160; One or more ValidationRules can be attached to a Binding, allowing for great flexibility in data validation.</p>
<p>Let’s look at our final point:</p>
<ul>
<li>The means to do conversion of the data through the binding itself </li>
</ul>
<p>Using WPF, we have the ability to bind objects of any type to a control, even if the type wouldn’t normally (directly) be editable or displayable within a control.&#160; WPF allows you to specify a converter to use to convert from the source type to the editing type, as well as handling the conversion back.&#160; This is done via <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx">IValueConverter</a>.&#160; By specifying your own value converter, you can bind, via both OneWay or TwoWay binding, any control to any type of object.&#160; For example, above, we bound our TextBox to “Feed.Link.AbsoluteUri”, which is a string.&#160; However, if the AbsoluteUri property didn’t exist, we could write a converter to convert from a <a href="http://msdn.microsoft.com/en-us/library/system.uri.aspx">Uri</a> to a string, and use that in our data binding.&#160; This would allow us to bind directly to “Feed.Link”, as follows:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">TextBox</span> <span class="attr">Grid</span>.<span class="attr">Row</span><span class="kwrd">=&quot;1&quot;</span> <span class="attr">Grid</span>.<span class="attr">Column</span><span class="kwrd">=&quot;1&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">TextBox.Text</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">Binding</span> <span class="attr">Path</span><span class="kwrd">=&quot;Feed.Link&quot;</span> <span class="attr">Mode</span><span class="kwrd">=&quot;OneWay&quot;</span><span class="kwrd">&gt;</span>
            <span class="kwrd">&lt;</span><span class="html">Binding.Converter</span><span class="kwrd">&gt;</span>
                <span class="kwrd">&lt;</span><span class="html">RssMVVM:StringToUriConverter</span> <span class="kwrd">/&gt;</span>
            <span class="kwrd">&lt;/</span><span class="html">Binding.Converter</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;/</span><span class="html">Binding</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">TextBox.Text</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">TextBox</span><span class="kwrd">&gt;</span></pre>
<p>This is critical to the flexibility of WPF’s data binding – we’re now directly binding a string (the TextBox.Text property) to a custom class (<a href="http://msdn.microsoft.com/en-us/library/system.uri.aspx">Uri</a>).&#160; We can now data bind to any type of object, which allows us to do very complex operations.&#160; For example, we can now display different images for Enum values (by having a converter that converts from the Enum value to an image).</p>
<p>To summarize, the data binding in Windows Presentation Foundation provides us with a simple, clean, powerful, and flexible means of displaying our properties inside our user interfaces, as well as automatically updating our properties when the user edits values within controls in our user interfaces.&#160; In addition, it does it in a way that’s completely declarative, with no code required.</p>
<p><em>* Although you can bind to any object, there are certain types of objects that work better.&#160; In particular, any object that implements INotifyPropertyChanged or derives from DependencyObject will allow for TwoWay binding to work properly.&#160; Collections should implement INotifyCollectionChanged or IBindingList in order to allow for proper TwoWay binding, as well.&#160; This isn’t a requirement, but it is worth mentioning, since it has a large impact on usability.</em></p>
<p><a href="http://reedcopsey.com/2009/12/28/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-5-commands/">… Continued in Part 5, Commands …</a></p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/HDs2MGhbBF4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/</feedburner:origLink></item>
		<item>
		<title>Better User and Developer Experiences – From Windows Forms to WPF with MVVM: Part 3, Our Application in WPF</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/fJ0BMC8Kj4k/</link>
		<comments>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 02:10:46 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=103</guid>
		<description><![CDATA[One common misconception I see when people start off with WPF is that they feel that it’s unapproachable, too complicated, and too unwieldy.&#160; There some fundamental shifts that every developer must deal with when the first switch to WPF, but they are actually fairly minor.&#160; You can program against the Windows Presentation Foundation API using [...]]]></description>
			<content:encoded><![CDATA[<p>One common misconception I see when people start off with WPF is that they feel that it’s unapproachable, too complicated, and too unwieldy.&#160; There some fundamental shifts that every developer must deal with when the first switch to WPF, but they are actually fairly minor.&#160; You can program against the <a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx">Windows Presentation Foundation</a> API using the same basic techniques that you used in Windows Forms.</p>
<p> <span id="more-103"></span>
<p>The first thing you’ll notice when working with WPF is the change in how the designer works.&#160; The same concepts are there – you can drag controls onto a <a href="http://msdn.microsoft.com/en-us/library/system.windows.window.aspx">Window</a> or a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.usercontrol(VS.95).aspx">UserControl</a>, and move them around, perform layout, etc.&#160; There are some differences in how things work, especially in regards to layout, but for the most part, a developer can still open a window, drag in controls, and place them using the same basic technique as the Windows Forms designer.</p>
<p>However, when this is done, the designer does something very different.&#160; In Windows Forms, the designer wrote our code for us; it created a partial class, and in the <em>.designer.cs</em> file, we got all of the code required to programmatically create our user interface.&#160; This fit well with Windows Form’s <a href="http://en.wikipedia.org/wiki/Imperative_programming">imperative programming</a> style.&#160; The WPF designer, on the other hand, builds its user interface by creating <em>.xaml</em> files instead, using the <a href="http://msdn.microsoft.com/en-us/library/ms752059.aspx">Extensible Application Markup Language</a>.&#160; Microsoft describes XAML as “A Declarative Language with Flow Control Support”; the key word here is “declarative.”&#160; WPF uses a <a href="http://en.wikipedia.org/wiki/Declarative_programming">declarative programming</a> model, at least for the creation of the user interface.&#160; Instead of specifying the steps required to build the user interface, the compiler uses a markup file (based on XML) that describes what should be displayed, not how to display it.</p>
<p>This is the single, fundamental change in thinking required to use WPF.&#160; Even then, this is handled completely by the designer, so technically, you can build an entire user interface and never even look at this, just as you could build a Windows Forms user interface and never look at the designer file.</p>
<p>WPF also provides similar, often identical, events on controls for each control type.&#160; For example, <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.button.aspx">Button</a> provides a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.buttonbase.click.aspx">Click event</a>, to which you can subscribe.&#160; The <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.aspx">TextBox</a> control provides a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox.text.aspx">Text</a> property you can set. This lets you wire up your event handlers in a manner that is nearly identical to Windows Forms.</p>
<p>For this part of our Series, we’re going to demonstrate this.&#160; We’re going to write the same application we wrote using <a href="http://reedcopsey.com/?p=100">Windows Forms in Part 2</a>, this time, using WPF.</p>
<p>First thing to notice &#8211; the application looks very similar:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2009/11/WPFFeedReaderMain.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="WPFFeedReaderMain" border="0" alt="WPFFeedReaderMain" src="http://reedcopsey.com/blog/wp-content/uploads/2009/11/WPFFeedReaderMain_thumb.png" width="350" height="484" /></a>The main differences are due to changes in the default styling of WPF’s controls vs. those of Windows Forms.&#160; Functionally, the application is identical.&#160; It uses the same <a href="http://reedcopsey.com/?p=90">Model classes</a>, completely unchanged.&#160; I performs the same functions, with the same basic behavior.&#160; We even structured it the same way, using a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.usercontrol(VS.95).aspx">UserControl</a> for the center section of the Window.</p>
<p>When we look at the code, we find something even more surprising – the code is nearly identical to our Windows Forms application!</p>
<p>For example, our “Load RSS Feed” button in our main Window class has a click event handler attached to it, and just like our Windows Forms application, it does nothing but load the Feed using the Model, and set a property in the UserControl.&#160; The only difference here is in the declaration of our method: instead of passing <strong>EventArgs e</strong>, we now pass <strong>RoutedEventArgs e</strong>.&#160; Otherwise, the code is identical:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ButtonUpdateFeed_Click(<span class="kwrd">object</span> sender, RoutedEventArgs e)
{
    <span class="kwrd">this</span>.feedControl.Feed = Feed.Read(<span class="kwrd">new</span> Uri(<span class="kwrd">this</span>.textBoxFeedUrl.Text));
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>Just like before, this sets the “Feed” property within our UserControl, but this time, <strong>the code in our UserControl is exactly the same as our Windows Forms code!&#160; </strong>We were able to copy the code, with absolutely no changes, from Windows Forms to WPF.&#160; Here is a small subset of that code, just to demonstrate that it hasn’t changed:</p>
<pre class="csharpcode"><span class="rem">// ... previous code from Windows Forms application</span>
    <span class="kwrd">this</span>.textBoxTitle.Text = <span class="kwrd">this</span>.Feed.Title;
    <span class="kwrd">this</span>.textBoxLink.Text = <span class="kwrd">this</span>.Feed.Link.AbsoluteUri;
    <span class="kwrd">this</span>.textBoxDescription.Text = <span class="kwrd">this</span>.Feed.Description;

    <span class="kwrd">foreach</span> (var item <span class="kwrd">in</span> <span class="kwrd">this</span>.Feed.Items)
    {
        <span class="kwrd">this</span>.listBoxFeeds.Items.Add(item.Title);
    }
<span class="rem">// ... continue with code from Windows Forms application</span></pre>
<p>In fact, when we look at our UserControl’s code behind file (the file that ends in .xaml.cs), the only differences we have between our WPF code and our Windows Forms code, through the entire Window and UserControl, are subtle differences in the method declaration, and setting “.Source” instead of “.Url” in our Main window, since WPF has different delegate declarations for its events and some subtle differences in control APIs.&#160; Otherwise, the code we wrote is identical, to the letter.</p>
<p>Windows Presentation Foundation, though new, does not force us as developers to change our programming style.&#160; We can do things the way we’ve always done them in Windows Forms, and continue forward with newer technology.&#160; We can even mix and match Windows Forms and WPF via <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.integration.elementhost.aspx">ElementHost</a> and <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.integration.windowsformshost.aspx">WindowsFormsHost</a>, which let us host WPF inside Windows Forms and Windows Forms inside WPF.</p>
<p>Here are the important points to realize from this part of the series:</p>
<ul>
<li>Although WPF is a completely new API, you can use the same <a href="http://en.wikipedia.org/wiki/Event-driven_programming">event-driven programming</a> style that you used in Windows Forms. </li>
<li>Most of the “new” features in WPF are optional.&#160; WPF can make a real application using the same techniques as Windows Forms, only now, some of the interface is defined <a href="http://en.wikipedia.org/wiki/Declarative_programming">declaratively</a> instead of being entirely <a href="http://en.wikipedia.org/wiki/Imperative_programming">imperative</a>. </li>
</ul>
<p>Hopefully, this mitigates some of the concern and fear of moving from Windows Forms to WPF.&#160; There really is no reason to avoid using Windows Presentation Foundation, even if I haven’t described (yet) the compelling reasons to migrate, and the numerous advantages of WPF.</p>
<p><a href="http://reedcopsey.com/2009/11/25/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-4-data-binding/">… Continued in Part 4, Data Binding …</a></p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/fJ0BMC8Kj4k" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/</feedburner:origLink></item>
		<item>
		<title>Better User and Developer Experiences – From Windows Forms to WPF with MVVM: Part 2, Our Application in Windows Forms</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/VDM1RXGRPXY/</link>
		<comments>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-2-our-application-in-windows-forms/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 00:53:10 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Windows Forms]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=100</guid>
		<description><![CDATA[In order to fully understand how and why to migrate from Windows Forms to WPF, and from WPF to WPF using MVVM, we need to understand Windows Forms.
When Microsoft first developed and released .NET, they provided a very clean, simple API for creating Windows applications based upon existing technologies: Windows Forms.&#160; The Windows Forms programming [...]]]></description>
			<content:encoded><![CDATA[<p>In order to fully understand how and why to migrate from Windows Forms to WPF, and from WPF to WPF using MVVM, we need to understand <a href="http://msdn.microsoft.com/en-us/library/dd30h2yb.aspx">Windows Forms</a>.</p>
<p>When Microsoft first developed and released .NET, they provided a very clean, simple API for creating Windows applications based upon existing technologies: Windows Forms.&#160; The Windows Forms programming model is an <a href="http://en.wikipedia.org/wiki/Event-driven_application">event based programming model</a>.&#160; This matches very well with prior Microsoft technologies, such as ATL and MFC, since the core of Windows Forms wraps around controls defined in the Windows API.</p>
<p> <span id="more-100"></span>
<p>In Windows Forms, you start with a “Form”, which corresponds to a Window in the desktop.&#160; The form contains multiple controls, each done via a wrapper around the Controls in the Windows API.&#160; Each control provides its own window handle (<a href="http://msdn.microsoft.com/en-us/library/aa383751(VS.85).aspx">HWND</a>, via <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.handle.aspx">Control.Handle</a>), which is basically a separate <a href="http://msdn.microsoft.com/en-us/library/ms632595(VS.85).aspx">Window</a>.&#160; When the application starts, you create a windows message pump by calling <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.application.run.aspx">Application.Run</a>, which maps the standard windows messages to their appropriate controls, which in turn raise <a href="http://msdn.microsoft.com/en-us/library/8627sbea.aspx">events</a> in the code for the Form.</p>
<p>In addition, a full designer was built which takes care of the initialization of the form, so the developer can graphically layout their controls on a form, and the appropriate C# code will be generated (inside the InitializeComponent method) on the fly.&#160; It will add event handlers for the developer, and map them to methods in the Form’s .cs file automatically, making the creation of quick GUIs very easy.</p>
<p>Microsoft also provided a means of compartmentalizing a form, breaking it into more managable, smaller pieces of functionality called a <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.usercontrol.aspx">UserControl</a>.&#160; A <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.usercontrol.aspx">UserControl</a> is basically the “guts” of a form that you can drop into another form, allowing both reuse in multiple forms, but also separation of logic into pieces to prevent a form from getting too large, in terms of code.</p>
<p>This is a very similar, comfortable model for developers who have used MFC, VB6, or even Delphi.&#160; The implementation details are slightly different, but the basic conceptual model was unchanged – design a form, hook up events, handle the events, always working with the message pump in code.&#160; This made adoption of the Windows Forms model very fast – it was familiar, and easy to transition from other technologies to Windows Forms.</p>
<p>For our series, we’re going to start here.&#160; Taking <a href="http://reedcopsey.com/?p=90">our Model</a>, the Feed and FeedItem classes described previously, we’re going to wire up a simple RSS Feed Reader application using Windows Forms.&#160; </p>
<p>This is a very simple application.&#160; For our purposes, the application must:</p>
<ul>
<li>Load the feed using the Model </li>
<li>Display the basic information about the Feed </li>
<li>Display the list of FeedItems in the Feed </li>
<li>Let the user choose a specific FeedItem </li>
<li>Allow the user to open a FeedItem’s original source in their browser </li>
<li>Display the FeedItem in a wrapped browser </li>
</ul>
<p>Here is a screenshot of our completed Windows Forms application:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2009/11/WinFormFeedReaderMain.png"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="WinFormFeedReaderMain" border="0" alt="WinFormFeedReaderMain" src="http://reedcopsey.com/blog/wp-content/uploads/2009/11/WinFormFeedReaderMain_thumb.png" width="363" height="484" /></a> There’s nothing fancy in this application, and the code should look very familiar to anyone who’s used Windows Forms.&#160; So, let’s look at how this works internally…</p>
<p>The “Feed Information” and “Select a Feed Item” section are broken into a separate UserControl for demonstration purposes.&#160; The user interface was completely generated inside of a designer, and the code was written for us.&#160; </p>
<p>When the user clicks on “Load RSS Feed”, a small event handler is run:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ButtonUpdateFeed_Click(<span class="kwrd">object</span> sender, EventArgs e)
{
    <span class="kwrd">this</span>.feedControl.Feed = Feed.Read(<span class="kwrd">new</span> Uri(<span class="kwrd">this</span>.textBox1.Text));
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>This sets the “Feed” property within our UserControl to a Feed (our Model).&#160; The UserControl has a “Feed” property, which specifies some code to run when the Feed is updated:</p>
<pre class="csharpcode"><span class="kwrd">public</span> Feed Feed
{
    get
    {
        <span class="kwrd">return</span> <span class="kwrd">this</span>.feed;
    }

    set
    {
        <span class="kwrd">this</span>.feed = <span class="kwrd">value</span>;
        <span class="kwrd">this</span>.ResetFeed();
    }
}</pre>
<p>This, in turn, calls the ResetFeed() method, which first calls ClearFeed() to cleanup the current UI, and then sets values inside each control:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ResetFeed()
{
    <span class="kwrd">this</span>.ClearFeed();

    <span class="kwrd">if</span> (<span class="kwrd">this</span>.Feed == <span class="kwrd">null</span>)
    {
        <span class="kwrd">return</span>;
    }

    <span class="kwrd">this</span>.textBoxTitle.Text = <span class="kwrd">this</span>.Feed.Title;
    <span class="kwrd">this</span>.textBoxLink.Text = <span class="kwrd">this</span>.Feed.Link.AbsoluteUri;
    <span class="kwrd">this</span>.textBoxDescription.Text = <span class="kwrd">this</span>.Feed.Description;

    <span class="kwrd">foreach</span> (var item <span class="kwrd">in</span> <span class="kwrd">this</span>.Feed.Items)
    {
        <span class="kwrd">this</span>.listBoxFeeds.Items.Add(item.Title);
    }
}

<span class="kwrd">private</span> <span class="kwrd">void</span> ClearFeed()
{
    <span class="kwrd">this</span>.listBoxFeeds.Items.Clear();
    <span class="kwrd">this</span>.textBoxTitle.Text = <span class="kwrd">string</span>.Empty;
    <span class="kwrd">this</span>.textBoxLink.Text = <span class="kwrd">string</span>.Empty;
    <span class="kwrd">this</span>.textBoxDescription.Text = <span class="kwrd">string</span>.Empty;
    <span class="kwrd">this</span>.textBoxItemTitle.Text = <span class="kwrd">string</span>.Empty;
    <span class="kwrd">this</span>.textBoxItemLink.Text = <span class="kwrd">string</span>.Empty;
    <span class="kwrd">this</span>.textBoxItemDescription.Text = <span class="kwrd">string</span>.Empty;
}</pre>
<p>Our user control gets filled in with all of the feed information by us.&#160; When the user chooses a feed in the ListBox control, we handle it via another event handler:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ListBoxFeeds_SelectedIndexChanged(<span class="kwrd">object</span> sender, EventArgs e)
{
    FeedItem item = <span class="kwrd">this</span>.Feed.Items[<span class="kwrd">this</span>.listBoxFeeds.SelectedIndex];
    <span class="kwrd">this</span>.textBoxItemTitle.Text = item.Title;
    <span class="kwrd">this</span>.textBoxItemLink.Text = item.Link.AbsoluteUri;
    <span class="kwrd">this</span>.textBoxItemDescription.Text = item.Description;

    <span class="kwrd">if</span> (<span class="kwrd">this</span>.UriChanged != <span class="kwrd">null</span>)
    {
        <span class="kwrd">this</span>.UriChanged(<span class="kwrd">this</span>, <span class="kwrd">new</span> UriChangedEventArgs(<span class="kwrd">new</span> Uri(<span class="kwrd">this</span>.textBoxItemLink.Text)));
    }
}</pre>
<p>When our selected feed item changes, we update the feed item’s controls, and also raise an event on our UserControl.&#160; Our main form subscribes to this event, and uses it to update the WebBrowser control sitting underneath our UserControl in the Form.</p>
<p>Finally, we have a button labeled “Open”, which has an event handler attached to it to open the Feed in our browser:</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> ButtonOpenLink_Click(<span class="kwrd">object</span> sender, EventArgs e)
{
    <span class="kwrd">if</span> (<span class="kwrd">this</span>.Feed != <span class="kwrd">null</span>)
    {
        FeedItem item = <span class="kwrd">this</span>.Feed.Items[<span class="kwrd">this</span>.listBoxFeeds.SelectedIndex];
        <span class="kwrd">if</span> (item != <span class="kwrd">null</span>)
        {
            System.Diagnostics.Process.Start(item.Link.AbsoluteUri);
        }
    }
}</pre>
<p>This should look familiar to most Windows Forms programmers.&#160; There are other ways to write this type of code, but this is very common, and seems quite indicative of how many Windows Forms programs are written.&#160; This is by no means meant to be a perfect example of a great Windows Forms application, but rather a typical, common way this application could have been written.</p>
<p>There are some important things to realize here.&#160; </p>
<ul>
<li>All of our logic is handled in events, triggered by the user interacting with the user interface in our Window. </li>
<li>Although the Windows Forms designer provides a nice interface, if you actually examine the code, the entire user interface is defined <a href="http://en.wikipedia.org/wiki/Imperative_programming">imperitively</a>, whether by us or by the designer. </li>
<li>The code, and therefore the logic, is really dependent on the type of control being used.&#160; For example, if we changed from a ListBox to some other type of control, we’d most likely need to change the code to compensate </li>
</ul>
<p><a href="http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-3-our-application-in-wpf/">… Continued in Part 3, Our Application in WPF …</a></p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/VDM1RXGRPXY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-2-our-application-in-windows-forms/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-2-our-application-in-windows-forms/</feedburner:origLink></item>
		<item>
		<title>Better User and Developer Experiences – From Windows Forms to WPF with MVVM: Part 1, The Model</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/s7lqbPQkIoc/</link>
		<comments>http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 01:12:25 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=90</guid>
		<description><![CDATA[Before we can make a user interface for a program, we need to know what the program is going to do.&#160; Hopefully, we have some logic we’re going to be exposing to our users.&#160; Underneath all of the beautiful user interfaces we build there is something that we’re trying to accomplish, some data we’re editing [...]]]></description>
			<content:encoded><![CDATA[<p>Before we can make a user interface for a program, we need to know what the program is going to do.&#160; Hopefully, we have some logic we’re going to be exposing to our users.&#160; Underneath all of the beautiful user interfaces we build there is something that we’re trying to accomplish, some data we’re editing or information we’re conveying.&#160; Before we can discuss how to make an effective user experience, we need to define the core information with which we are working.</p>
<p> <span id="more-90"></span>When we discuss software architecturally, the core elements of our program are the “Model”.&#160; The terminology comes from <a href="http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science)">architectural design patterns</a>, and goes back pretty far.&#160; The “Model” is the one thing in most user interface patterns that hasn’t changed, and is the same terminology used all the way back with Smalltalk in the 70’s when Trygve Reenskaug first described the <a href="http://en.wikipedia.org/wiki/Model-view-controller">Model-View-Controller</a> pattern.
</p>
<p>When we’re talking about the Model, we’re talking about the domain-specific data and logic – the “guts” inside the program itself.&#160; In an ideal world, the program should be able to, at least theoretically and architecturally, work without the user interface being present at all, <strong>provided it has the appropriate information</strong> passed to it.&#160; The core business logic, in an ideal world, doesn’t need or want to know anything about how it’s being used – that’s outside of its <a href="http://en.wikipedia.org/wiki/Concern_(computer_science)">concern</a>.</p>
<p>Your business logic should know about your business, and nothing else.&#160; This is key to maintaining an effective <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a> within the design of our program.&#160; This is also very useful for maintaining a program over time.&#160; Keeping the model separate makes it much easier to extend an application into other realms without duplication of code or breaking a deployed application.&#160; For example, if your business logic is completely isolated, you could potentially switch, without changing your business logic, from using a desktop, client-side application to using a command line, script based version of your application.&#160; In some situations, you can even take the same logic and host it, accessing it remotely via a web page.</p>
<p>In most cases, its easiest to think of the Model as the data.&#160; If you are making an application to edit customer information, the customer information (data) is the Model.&#160; The model can also encapsulate logic, however.&#160; If you have a service that needs to be called as part of your business logic when data is updated, the service itself can be thought of as part of the model.&#160; When you talk about your program, when you discuss what <strong>functions the program performs</strong>, such as it “works on” this (data) or “performs this task” (logic), you are talking about the model.&#160; Any time you discuss <strong>how the user interacts with the program</strong>, however, you are talking outside of the concern of the Model.</p>
<p>I want to mention, as a side note, one other thing here, that I often see as a point of confusion.&#160; If you have an application with a full, multi-tier data access layer, all of the data access and logic layers are part of (or under) the Model.&#160; For our purposes, we treat data and logic tiers as an internal, private implementation detail of the Model.&#160; Here, the business logic layer acts as the Model&#8217;s public API, and we use that as our Model.&#160; Presentation is separate from the Model, but the things the user &quot;works on&quot; (the data and domain specific logic to manipulate the data) are part of the Model.</p>
<p>For our series, we’re going to work with a simple program that is just an RSS feed reader.&#160; When we’re talking about the feed reader applications, all three versions of our application we will develop use the same Model.&#160; The public API of the Model is nothing but 2 classes: a <strong>Feed</strong> and a <strong>FeedItem</strong>.&#160; The Feed class has some properties (Title, Description, etc), as well as a collection of FeedItem instances.&#160; The FeedItem class contains properties for information about each item in the feed, including a Title, a Link to the original item, and a Description of the feed item.&#160; The Feed class also has some logic – it has a static method that allows it to create a Feed given a Uri.</p>
<p>There is one important thing to remember about our Feed and FeedItem classes – they just describe data, and provide a means to load it.&#160; They do not describe, in any way, how to edit or display the data.&#160; Because the Model is all about data, and not about presentation or manipulation of that data by the user, we can use the same assembly, unchanged, in all three versions of our application.</p>
<p><a href="http://reedcopsey.com/2009/11/24/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-2-our-application-in-windows-forms/">… Continued in Part 2, Our Application in Windows Forms …</a></p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/s7lqbPQkIoc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/</feedburner:origLink></item>
		<item>
		<title>Better User and Developer Experiences – From Windows Forms to WPF with MVVM: Introduction</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/EIzEVgSZKik/</link>
		<comments>http://reedcopsey.com/2009/11/20/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-introduction/#comments</comments>
		<pubDate>Sat, 21 Nov 2009 01:26:39 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=89</guid>
		<description><![CDATA[I frequently talk to people trying to decide, for a new project, between Windows Forms and Windows Presentation Foundation.&#160; After spending time with WPF, I feel there is no reason to choose Windows Forms for new development.&#160; WPF, when used correctly, is far superior, both in terms of user experience, but also developer productivity.
I feel [...]]]></description>
			<content:encoded><![CDATA[<p>I frequently talk to people trying to decide, for a new project, between Windows Forms and Windows Presentation Foundation.&#160; After spending time with WPF, I feel there is no reason to choose Windows Forms for new development.&#160; WPF, when used correctly, is far superior, both in terms of user experience, but also developer productivity.</p>
<p>I feel that the confusion around choosing WPF really stems from a lack of understanding about WPF.&#160; Even people on my own team have been overwhelmed trying to understand how the different pieces of WPF fit together, and how to apply the new concepts introduced with WPF effectively.&#160; In order to address this, I’m going to break this down into a few simple pieces, and show the migration in terms of thought required to transition from being a good Windows Forms developer to an effective WPF developer.</p>
</p>
<p> <span id="more-89"></span>
</p>
<p>Windows Presentation Foundation is huge.&#160; Do not doubt it.&#160; It is huge, both in terms of scope, but also in terms of the radically different approach it takes to developing user interfaces than other technologies.&#160; Don’t let the scope frighten you, however – it is very well thought out, and very usable, once you understand some of the basic concepts.</p>
<p>In addition to the huge scope of WPF, new design patterns have evolved to take advantage of the new features introduced by this framework.&#160; The most commonly referenced one, in terms of WPF, seems to be MVVM, or Model-View-ViewModel.&#160; The Model-View-ViewModel pattern was inspired by some of the features in WPF, and seems perfectly fit for WPF, so many developers advocate it (with good reason) for use with WPF.</p>
<p>Again, don’t let this frighten or discourage you… MVVM isn’t about making WPF more difficult, it’s about making WPF usable in a quick, efficient manner.&#160; Learning MVVM actually makes understanding WPF easier, not more difficult.</p>
<p>The issue here is that WPF is large, and the framework doesn’t force you into a single way of working.&#160; There are lots of ways to work with WPF, including doing nearly the exact thing you’re used to with Windows Forms!&#160; This is part of the power and flexibility of WPF, but also a trap to watch for and to avoid.&#160; MVVM helps guide and force you to take advantage of WPF’s new features effectively, insulating you from common pitfalls and mistakes.</p>
<p>For this series, I’m going to start by showing a simple Windows Forms application – an RSS Feed Reader, and demonstrate converting it to WPF.&#160; I’ll start with a strait conversion – and demonstrate how you can make WPF look and work exactly the same as you can with Windows Forms.&#160; I’ll then explain, in details, some of the new ways of thinking that are pervasive within WPF, and show how this should change your way of thinking about user interfaces.</p>
<p>In order to do this, we’ll work with four separate projects – which include three completely different versions of the same application.&#160; The goal here isn’t to use WPF to make the application “pretty” or “flashy”, rather, it’s to show how you can use WPF to make an application more developer friendly, including making it cleaner, more logical, easier to maintain, and more testable.</p>
<p><a href="http://reedcopsey.com/2009/11/23/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-part-1-the-model/">… Continued in Part 1, The Model …</a></p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/EIzEVgSZKik" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/20/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-introduction/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2009/11/20/better-user-and-developer-experiences-from-windows-forms-to-wpf-with-mvvm-introduction/</feedburner:origLink></item>
		<item>
		<title>Synchronizing .NET 4 Tasks with the UI Thread</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/VCSAp42wJ50/</link>
		<comments>http://reedcopsey.com/2009/11/17/synchronizing-net-4-tasks-with-the-ui-thread/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 00:38:49 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=88</guid>
		<description><![CDATA[While attending the Patterns of Parallel Programming Workshop at PDC, I picked up a very interesting tidbit from Stephen Toub’s talk: the new Task pattern in .NET 4 has built-in support for synchronization with the UI thread.&#160; This makes writing parallel applications that interact with the user interface easier than ever before.
 
The key to [...]]]></description>
			<content:encoded><![CDATA[<p>While attending the <a href="http://microsoftpdc.com/Sessions/Patterns-of-Parallel-Programming">Patterns of Parallel Programming Workshop</a> at <a href="http://microsoftpdc.com/">PDC</a>, I picked up a very interesting tidbit from <a href="http://blogs.msdn.com/toub/">Stephen Toub</a>’s talk: the new Task pattern in .NET 4 has built-in support for synchronization with the UI thread.&#160; This makes writing parallel applications that interact with the user interface easier than ever before.</p>
<p> <span id="more-88"></span>
<p>The key to this is the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.fromcurrentsynchronizationcontext(VS.100).aspx">TaskScheduler.FromCurrentSynchronizationContext()</a> method.&#160; This method creates a scheduler from the current <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext(VS.100).aspx">SynchronizationContext</a>, automatically choosing the appropriate context.&#160; This scheduler can then be used by nearly all of the TaskFactory methods to generate a task.</p>
<p>As an example, here is a very simple Form.Load event handler for a demo Windows Forms application which creates a task which will execute in the background when the form loads.&#160; The task runs some (fake) work, and occasionally uses tasks, as well as a continuation task, to update the user interface.</p>
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">void</span> Form1_Load(<span class="kwrd">object</span> sender, EventArgs e)
{
    <span class="rem">// This requires a label titled &quot;label1&quot; on the form...</span>
    <span class="rem">// Get the UI thread's context</span>
    var context = TaskScheduler.FromCurrentSynchronizationContext();

    <span class="kwrd">this</span>.label1.Text = <span class="str">&quot;Starting task...&quot;</span>;

    <span class="rem">// Start a task - this runs on the background thread...</span>
    Task task = Task.Factory.StartNew( () =&gt;
        {
            <span class="rem">// Do some fake work...</span>
            <span class="kwrd">double</span> j = 100;
            Random rand = <span class="kwrd">new</span> Random();
            <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; 10000000; ++i)
            {
                j *= rand.NextDouble();
            }

            <span class="rem">// It's possible to start a task directly on</span>
            <span class="rem">// the UI thread, but not common...</span>
            var token = Task.Factory.CancellationToken;
            Task.Factory.StartNew(() =&gt;
            {
                <span class="kwrd">this</span>.label1.Text = <span class="str">&quot;Task past first work section...&quot;</span>;
            }, token, TaskCreationOptions.None, context);

            <span class="rem">// Do a bit more work</span>
            Thread.Sleep(1000);
        })
        <span class="rem">// More commonly, we'll continue a task with a new task on</span>
        <span class="rem">// the UI thread, since this lets us update when our</span>
        <span class="rem">// &quot;work&quot; completes.</span>
        .ContinueWith(_ =&gt; <span class="kwrd">this</span>.label1.Text = <span class="str">&quot;Task Complete!&quot;</span>, context);
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>The beauty of this may not be apparent at first glance, but look closely at the threading methods.&#160; They work with the SynchronizationContext instance, which was generated by the TaskFactory for us.&#160; Nowhere do we explicitly say to use Control.Invoke or any other Windows Forms construct.&#160; In fact, this code will work exactly the same way, unchanged, on WPF.&#160; The library handles assigning us the correct SynchronizationContext for us.&#160; In Windows Forms, it will generate a context which passes everything to the message loop.&#160; In WPF, it will automatically generated a context which uses the Dispatcher to push messages back into the WPF message queue.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/VCSAp42wJ50" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/17/synchronizing-net-4-tasks-with-the-ui-thread/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2009/11/17/synchronizing-net-4-tasks-with-the-ui-thread/</feedburner:origLink></item>
		<item>
		<title>Thread specific data becomes easier in .NET 4.0 via ThreadLocal&lt;T&gt;</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/vZbpMJvOJ40/</link>
		<comments>http://reedcopsey.com/2009/11/12/thread-specific-data-becomes-easier-in-net-4-0-via-threadlocalt/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 21:55:49 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/?p=87</guid>
		<description><![CDATA[Occasionally, when dealing with multithreaded code, there are uses for data that is kept in a manner that is unique to the currently running thread.&#160; This is accomplished via using Thread-local storage.&#160; Typically, in .NET 3.5, this was handled via the [ThreadStatic] attribute, however, this puts certain restrictions on usage.&#160; The main problem with ThreadStatic [...]]]></description>
			<content:encoded><![CDATA[<p>Occasionally, when dealing with multithreaded code, there are uses for data that is kept in a manner that is unique to the currently running thread.&#160; This is accomplished via using <a href="http://en.wikipedia.org/wiki/Thread-local_storage">Thread-local storage</a>.&#160; Typically, in .NET 3.5, this was handled via the <a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute.aspx">[ThreadStatic]</a> attribute, however, this puts certain restrictions on usage.&#160; The main problem with ThreadStatic is that it is exactly that – static data stored per thread.&#160; This can be problematic, especially if you’re using ThreadPool threads, as the data is never released cleanly.&#160; </p>
<p>Currently, if you want to use data kept at a local scope with a copy per thread, the solution is to use a <a href="http://msdn.microsoft.com/en-us/library/system.localdatastoreslot.aspx">LocalDataStoreSlot</a> to manage your threaded data.&#160; This works, but is not very developer-friendly.&#160; It is not type-safe; all data is stored as a System.Object.&#160; It is clunky at best to use, especially if you want to free, as you have to use and track strings with named data slots in order to release the memory.&#160; Version 4 of the .NET Framework fixes all of these issues by introducing <a href="http://msdn.microsoft.com/en-us/library/dd642243(VS.100).aspx">ThreadLocal&lt;T&gt;</a>.</p>
<p> <span id="more-87"></span>
<p>The new <a href="http://msdn.microsoft.com/en-us/library/dd642243(VS.100).aspx">ThreadLocal&lt;T&gt;</a> class provides us with a strongly typed, locally scoped object we can use to setup data that is kept separate for each thread.&#160; This allows us to use data stored per thread, without having to introduce static variables into our types.&#160; Internally, the ThreadLocal instance will automatically setup the static data, manage its lifetime, do all of the casting to and from our specific type.&#160; This makes developing much simpler.</p>
<p>Here’s a simple but complete example showing how this is used:</p>
<pre class="csharpcode"><span class="kwrd">namespace</span> CSharpConsoleApplication
{
    <span class="kwrd">using</span> System;
    <span class="kwrd">using</span> System.Threading;
    <span class="kwrd">using</span> System.Threading.Tasks;

    <span class="kwrd">class</span> Program
    {

        <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
        {
            <span class="rem">// Create our ThreadLocal&lt;T&gt;, with a Func&lt;T&gt; used to initialize</span>
            <span class="kwrd">using</span> (ThreadLocal&lt;<span class="kwrd">int</span>&gt; dataPerThread =
                    <span class="kwrd">new</span> ThreadLocal&lt;<span class="kwrd">int</span>&gt;(() =&gt; Thread.CurrentThread.ManagedThreadId))
            {
                <span class="rem">// Loop a few times, to see the output</span>
                Parallel.For(0, 10, (i) =&gt;
                    {
                        Console.WriteLine(<span class="str">&quot;dataPerThread {0}/{1} for iteration {2}&quot;</span>,
                                     dataPerThread.IsValueCreated, dataPerThread.Value, i);
                    });
            }

            <span class="rem">// Wait for a keypress to exit</span>
            Console.WriteLine(<span class="str">&quot;Press any key to exit...&quot;</span>);
            Console.ReadKey();
        }
    }
}</pre>
<style type="text/css">
<p>.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>
<p>When we run, we’ll get results similar to the following:</p>
<pre>dataPerThread False/9 for iteration 0
dataPerThread True/9 for iteration 2
dataPerThread False/10 for iteration 1
dataPerThread True/10 for iteration 5
dataPerThread True/10 for iteration 6
dataPerThread True/10 for iteration 7
dataPerThread True/10 for iteration 8
dataPerThread True/10 for iteration 9
dataPerThread False/12 for iteration 4
dataPerThread True/9 for iteration 3
Press any key to exit...</pre>
<p>Your results will obviously be different, as the order is somewhat random.&#160; (We are multi-threading here!)</p>
<p>Here are a few things to note about this sample and these results:</p>
<p>First, when we create the ThreadLocal&lt;int&gt; instance, we have the option of providing a <a href="http://msdn.microsoft.com/en-us/library/bb534960(VS.100).aspx">Func&lt;T&gt;</a> to the <a href="http://msdn.microsoft.com/en-us/library/dd642263(VS.100).aspx">ThreadLocal&lt;T&gt;’s Constructor</a>.&#160; This allows us to provide an initialization routine which will be used the first time a given thread accesses the Value property.&#160; This greatly eases our construction burden, since we can just wrap everything in a delegate (potentially using closures around our class variables) to have complex initialization of our type without having to “think about” it during our work.</p>
<p>Second, when we first access our dataPerThread variable, it is uninitialized.&#160; If we need to do complex initialization, we can check the <a href="http://msdn.microsoft.com/en-us/library/dd642279(VS.100).aspx">ThreadLocal&lt;T&gt;.IsValueCreated</a> property.&#160; This will tell us whether or not a specific value has been created for the <strong>currently running thread</strong>.&#160; When we run the sample, you can see this – the first time a specific thread (the first number, either 9, 10, or 12) accesses dataPerThread, IsValueCreated returns false.&#160; When we then read the value, our Func&lt;T&gt; will execute, and set the data to the current managed thread ID.&#160; The subsequent times we try to read the data, it’s already been created.</p>
<p>Third, <a href="http://msdn.microsoft.com/en-us/library/dd642243(VS.100).aspx">ThreadLocal&lt;T&gt;</a> implements <a href="http://msdn.microsoft.com/en-us/library/system.idisposable(VS.100).aspx">IDisposable</a>.&#160; This provides a much simpler way of handling cleanup than trying to deal with static variables per thread.</p>
<p>So the final question I’ll address here: Why is this useful, and where would I want to use this class?&#160; In my case, I already have one very good use case.&#160; I will be using ThreadLocal&lt;T&gt; in order to handle a thread-specific cache.</p>
<p>We have some algorithms which are parallelizable.&#160; However, as we run from one case to the next, there is a chance we can save quite a bit of computation by caching and reusing certain steps, <a href="http://en.wikipedia.org/wiki/Memoizing">momoizing the results</a>.&#160; However, since we’re threading the algorithm, sharing this cache amongst the threads is problematic – it requires adding locking within the algorithm in order to have a thread-safe cache.&#160; The locking nearly wipes out the speed gains we achieve via the caching.</p>
<p>By using ThreadLocal&lt;T&gt; to store our cache information, each thread can have it’s own copy of the cache, created once per run (local scope).&#160; This provides us with completely threadsafe, lock-free memoization, at the cost of two threads potentially recalculating results.&#160; Profiling our algorithm proved that this provided a dramatic speed improvement.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/vZbpMJvOJ40" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2009/11/12/thread-specific-data-becomes-easier-in-net-4-0-via-threadlocalt/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2009/11/12/thread-specific-data-becomes-easier-in-net-4-0-via-threadlocalt/</feedburner:origLink></item>
	</channel>
</rss>
