<?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>Thu, 25 Apr 2013 16:06:00 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<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>Launching a WPF Window in a Separate Thread, Part 1</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/K9gdT0R182Q/</link>
		<comments>http://reedcopsey.com/2011/11/28/launching-a-wpf-window-in-a-separate-thread-part-1/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 20:32:38 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2011/11/28/launching-a-wpf-window-in-a-separate-thread-part-1/</guid>
		<description><![CDATA[Typically, I strongly recommend keeping the user interface within an application’s main thread, and using multiple threads to move the actual “work” into background threads.&#160; However, there are rare times when creating a separate, dedicated thread for a Window can be beneficial.&#160; This is even acknowledged in the MSDN samples, such as the Multiple Windows, [...]]]></description>
				<content:encoded><![CDATA[<p>Typically, I strongly recommend keeping the user interface within an application’s main thread, and using multiple threads to move the actual “work” into background threads.&#160; However, there are rare times when creating a separate, dedicated thread for a Window can be beneficial.&#160; This is even acknowledged in the MSDN samples, such as the Multiple Windows, Multiple Threads* sample.&#160; However, doing this <em>correctly</em> is difficult.&#160; Even the referenced MSDN sample has major flaws, and will fail horribly in certain scenarios.&#160; To ease this, I wrote a small class that alleviates some of the difficulties involved.</p>
<p><span id="more-321"></span>
<p>The MSDN Multiple Windows, Multiple Threads Sample* showed how to launch a new thread with a WPF Window, and will work in most cases.&#160; The sample code (commented and slightly modified) works out to the following:</p>
<pre class="csharpcode"><span class="rem">// Create a thread</span>
Thread newWindowThread = <span class="kwrd">new</span> Thread(<span class="kwrd">new</span> ThreadStart( () =&gt;
{
    <span class="rem">// Create and show the Window</span>
    Window1 tempWindow = <span class="kwrd">new</span> Window1();
    tempWindow.Show();
    <span class="rem">// Start the Dispatcher Processing</span>
    System.Windows.Threading.Dispatcher.Run();
}));
<span class="rem">// Set the apartment state</span>
newWindowThread.SetApartmentState(ApartmentState.STA);
<span class="rem">// Make the thread a background thread</span>
newWindowThread.IsBackground = <span class="kwrd">true</span>;
<span class="rem">// Start the thread</span>
newWindowThread.Start();</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 sample creates a thread, marks it as single threaded apartment state, and starts the Dispatcher on that thread. That is the minimum requirements to get a Window displaying and handling messages correctly, but, unfortunately, has some serious flaws. </p>
<p>*Note: The referenced sample is no longer available as of 2013.  A new <a href="http://msdn.microsoft.com/en-us/library/ms771272%28v=vs.90%29.aspx">Multithreaded Web Browser Sample</a> shows a similar technique and code</a></p>
<p>The first issue – the created thread will run continuously until the application shuts down, given the code in the sample.&#160; The problem is that the ThreadStart delegate used ends with running the Dispatcher.&#160; However, nothing ever stops the Dispatcher processing.&#160; The thread was created as a Background thread, which prevents it from keeping the application alive, but the Dispatcher will continue to pump dispatcher frames until the application shuts down.</p>
<p>In order to fix this, we need to call <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.invokeshutdown.aspx">Dispatcher.InvokeShutdown</a> after the Window is closed.&#160; This would require modifying the above sample to subscribe to the Window’s Closed event, and, at that point, shutdown the Dispatcher:</p>
<pre class="csharpcode"><span class="rem">// Create a thread</span>
Thread newWindowThread = <span class="kwrd">new</span> Thread(<span class="kwrd">new</span> ThreadStart( () =&gt;
{
    Window1 tempWindow = <span class="kwrd">new</span> Window1();
    <span class="rem">// When the window closes, shut down the dispatcher</span>
    tempWindow.Closed += (s,e) =&gt; 
       Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);

    tempWindow.Show();
    <span class="rem">// Start the Dispatcher Processing</span>
    System.Windows.Threading.Dispatcher.Run();
}));
<span class="rem">// Setup and start thread as before</span></pre>
<p>This eliminates the first issue.&#160; Now, when the Window is closed, the new thread’s Dispatcher will shut itself down, which in turn will cause the thread to complete.</p>
<p>The above code will work correctly for most situations.&#160; However, there is still a potential problem which could arise depending on the content of the Window1 class.&#160; This is particularly nasty, as the code could easily work for most windows, but fail on others.</p>
<p>The problem is, at the point where the Window is constructed, there is no active SynchronizationContext.&#160; This is unlikely to be a problem in most cases, but is an absolute requirement if there is code within the constructor of Window1 which relies on a context being in place.</p>
<p>While this sounds like an edge case, it’s fairly common.&#160; For example, if a BackgroundWorker is started within the constructor, or a TaskScheduler is built using TaskScheduler.FromCurrentSynchronizationContext() with the expectation of synchronizing work to the UI thread, an exception will be raised at some point.&#160; Both of these classes rely on the existence of a proper context being installed to SynchronizationContext.Current, which happens automatically, but not until Dispatcher.Run is called.&#160; In the above case, SynchronizationContext.Current will return null during the Window’s construction, which can cause exceptions to occur or unexpected behavior.</p>
<p>Luckily, this is fairly easy to correct.&#160; We need to do three things, in order, prior to creating our Window:</p>
<ul>
<li>Create and initialize the Dispatcher for the new thread manually </li>
<li>Create a synchronization context for the thread which uses the Dispatcher </li>
<li>Install the synchronization context </li>
</ul>
<p>Creating the Dispatcher is quite simple – The <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.currentdispatcher.aspx">Dispatcher.CurrentDispatcher</a> property gets the current thread’s Dispatcher and “<em>creates a new Dispatcher if one is not already associated with the thread.</em>”&#160; Once we have the correct Dispatcher, we can create a SynchronizationContext which uses the dispatcher by creating a <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatchersynchronizationcontext.aspx">DispatcherSynchronizationContext</a>.&#160; Finally, this synchronization context can be installed as the current thread’s context via <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.setsynchronizationcontext.aspx">SynchronizationContext.SetSynchronizationContext</a>.&#160; These three steps can easily be added to the above via a single line of code:</p>
<pre class="csharpcode"><span class="rem">// Create a thread</span>
Thread newWindowThread = <span class="kwrd">new</span> Thread(<span class="kwrd">new</span> ThreadStart( () =&gt;
{
    <span class="rem">// Create our context, and install it:</span>
    SynchronizationContext.SetSynchronizationContext(
        <span class="kwrd">new</span> DispatcherSynchronizationContext(
            Dispatcher.CurrentDispatcher));

    Window1 tempWindow = <span class="kwrd">new</span> Window1();
    <span class="rem">// When the window closes, shut down the dispatcher</span>
    tempWindow.Closed += (s,e) =&gt; 
       Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);

    tempWindow.Show();
    <span class="rem">// Start the Dispatcher Processing</span>
    System.Windows.Threading.Dispatcher.Run();
}));
<span class="rem">// Setup and start thread as before</span></pre>
<p>This now forces the synchronization context to be in place before the Window is created and correctly shuts down the Dispatcher when the window closes.</p>
<p>However, there are quite a few steps.&#160; In my next post, I’ll show how to make this operation more reusable by creating a class with a far simpler API…</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/K9gdT0R182Q" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2011/11/28/launching-a-wpf-window-in-a-separate-thread-part-1/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2011/11/28/launching-a-wpf-window-in-a-separate-thread-part-1/</feedburner:origLink></item>
		<item>
		<title>Reflections on GiveCamp</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/TwqJFEfA7I0/</link>
		<comments>http://reedcopsey.com/2011/10/25/reflections-on-givecamp/#comments</comments>
		<pubDate>Wed, 26 Oct 2011 00:20:48 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[Community]]></category>
		<category><![CDATA[Professional]]></category>
		<category><![CDATA[Charity]]></category>
		<category><![CDATA[GiveCamp]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2011/10/25/reflections-on-givecamp/</guid>
		<description><![CDATA[I participated in the Seattle GiveCamp over the weekend, and am entirely impressed.&#160; GiveCamp is a great event – I especially like how rewarding it is for everybody involved.&#160; I strongly encourage any and all developers to watch for future GiveCamp events, and consider participating, for many reasons… GiveCamp provides real value to organizations that [...]]]></description>
				<content:encoded><![CDATA[<p>I participated in the <a href="http://www.seattlegivecamp.org/">Seattle GiveCamp</a> over the weekend, and am entirely impressed.&#160; <a href="http://givecamp.org/">GiveCamp</a> is a great event – I especially like how rewarding it is for everybody involved.&#160; I strongly encourage any and all developers to <a href="https://twitter.com/#!/givecamp">watch for future GiveCamp</a> events, and consider participating, for many reasons…</p>
<p><span id="more-314"></span>
<ul>
<li><strong>GiveCamp provides real value to organizations that truly need help.&#160; </strong></li>
</ul>
<p>The Seattle event alone succeeded in helping <a href="http://seattlegivecamp.wikispaces.com/">sixteen non-profit organizations</a> in many different ways.&#160; The projects involved varied dramatically, including website redesigns, SEO, reworking data management workflows, and even game development.&#160; </p>
<p>Many non-profits have a strong need for good, quality technical help.&#160; However, nearly every non-profit organization has an incredibly limited budget.&#160; GiveCamp is a way to really give back, and provide incredibly valuable help to organizations that truly benefit.</p>
<p>My experience has shown many developers to be incredibly generous – this is a chance to dedicate your energy to helping others in a way that really takes advantage of your expertise.&#160; Your time as a developer is incredibly valuable, and this puts something of incredible value directly into the hands of places its needed.</p>
<p>First, and foremost, GiveCamp is about providing technical help to non-profit organizations in need.</p>
<ul>
<li><strong>GiveCamp can make you a better developer.&#160; </strong></li>
</ul>
<p>This is a fantastic opportunity for us, as developers, to work with new people, in a new setting.&#160; The incredibly short time frame (one weekend for a deliverable project) and intense motivation to succeed provides a huge opportunity for learning from peers.&#160; </p>
<p>I’d personally like to thank off the developers with whom I worked – I learned something from each and every one of you.&#160; I hope to see and work with all of you again someday.</p>
<ul>
<li><strong>GiveCamp provides an opportunity for you to work outside of your comfort zone. </strong></li>
</ul>
<p>While it’s always nice to be an expert, it’s also valuable to work on a project where you have little or no direct experience.&#160; My team focused on a complete reworking of our organizations message and a complete new website redesign and deployment using <a href="http://wordpress.org/">WordPress</a>.&#160; </p>
<p>While I’d used WordPress for my blog, and had some experience, this is completely unrelated to my professional work.&#160; In fact, nobody on our team normally worked directly with the technologies involved – yet together we managed to succeed in delivering our goals.&#160; </p>
<p>As developers, it’s easy to want to stay abreast of new technology surrounding our expertise, but its rare that we get a chance to sit down and work on something <em>practical</em> that is completely outside of our normal realm of work.&#160; I’m a desktop developer by trade, and spent much of the weekend working with CSS and Photoshop.&#160; Many of the projects organizations <em>need</em> don’t match perfectly with the skill set in the room – yet all of the software professionals rose to the occasion and delivered practical, usable applications.</p>
<ul>
<li><strong>GiveCamp is a short term, known commitment. </strong></li>
</ul>
<p>While this seems obvious, I think it’s an important aspect to remember.&#160; This is a huge part of what makes it successful – you can work, completely focused, on a project, then walk away completely when you’re done.&#160; There is no expectation of continued involvement.&#160; While many of the professionals I’ve talked to are willing to contribute some amount of their time beyond the camp, this is not expected.</p>
<p>The freedom this provides is immense.&#160; In addition, the motivation this brings is incredibly valuable.&#160; Every developer in the room was very focused on delivering in time – you have one shot to get it as good as possible, and leave it with the organization in a way that can be maintained by them.&#160; This is a rare experience – and excellent practice at time management for everyone involved.</p>
<ul>
<li><strong>GiveCamp provides a great way to meet and network with your peers. </strong></li>
</ul>
<p>Not only do you get to network with other software professionals in your area – you get to network with amazing people.&#160; Every single person in the room is there to try to help people.&#160; The balance of altruism, intelligence, and expertise in the room is something I’ve never before experienced.</p>
<p>During the presentations of what was accomplished, I felt blessed to participate.&#160; I know many people in the room were incredibly touched by the level of dedication and accomplishment over the weekend.</p>
<ul>
<li><strong>GiveCamp is fun. </strong></li>
</ul>
<p>At the end of the experience, I would have signed up again, even if it was a painful, tedious weekend – merely due to the amazing accomplishments achieved throughout the event.&#160; However, the event is <em>fun.</em>&#160; </p>
<p>Everybody I talked to, the entire weekend, was having a good time.&#160; While there were many faces focused into a near grimace at times (including mine, I’ll admit), this was always in response to a particularly challenging problem or task.&#160; The challenges just added to the overall enjoyment of the weekend – part of why I became a developer in the first place is my love for challenge and puzzles, and a short deadline using unfamiliar technology provided plenty of opportunity for puzzles.&#160; As soon as people would stand up, it was another smile.</p>
<p>&#160;</p>
<p>If you’re a developer, I’d recommend looking at <a href="http://givecamp.org/">GiveCamp</a> more closely.&#160; Watch for an event in your area.&#160; If there isn’t one, consider building a team and <a href="http://givecamp.org/home/for-organizers/">organizing an event</a>.&#160; The experience is worth the commitment.&#160; </p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/TwqJFEfA7I0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2011/10/25/reflections-on-givecamp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2011/10/25/reflections-on-givecamp/</feedburner:origLink></item>
		<item>
		<title>Setting useLegacyV2RuntimeActivationPolicy At Runtime</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/sgwC4sP-EAs/</link>
		<comments>http://reedcopsey.com/2011/09/15/setting-uselegacyv2runtimeactivationpolicy-at-runtime/#comments</comments>
		<pubDate>Thu, 15 Sep 2011 20:58:12 +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>
		<category><![CDATA[Interop]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2011/09/15/setting-uselegacyv2runtimeactivationpolicy-at-runtime/</guid>
		<description><![CDATA[Version 4.0 of the .NET Framework included a new CLR which is almost entirely backwards compatible with the 2.0 version of the CLR.&#160; However, by default, mixed-mode assemblies targeting .NET 3.5sp1 and earlier will fail to load in a .NET 4 application.&#160; Fixing this requires setting useLegacyV2RuntimeActivationPolicy in your app.Config for the application.&#160; While there [...]]]></description>
				<content:encoded><![CDATA[<p>Version 4.0 of the .NET Framework included a new CLR which is <em>almost</em> entirely backwards compatible with the 2.0 version of the CLR.&#160; However, by default, mixed-mode assemblies targeting .NET 3.5sp1 and earlier will fail to load in a .NET 4 application.&#160; Fixing this requires setting <a href="http://msdn.microsoft.com/en-us/library/bbx34a2h.aspx">useLegacyV2RuntimeActivationPolicy</a> in your app.Config <em>for the application.&#160; </em>While there are <a href="http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx">many good reasons for this decision</a>, there are times when this is extremely frustrating, especially when writing a library.&#160; As such, there are (rare) times when it would be beneficial to set this in code, at runtime, as well as verify that it’s running correctly prior to receiving a <a href="http://msdn.microsoft.com/en-us/library/system.io.fileloadexception.aspx">FileLoadException</a>.</p>
<p><span id="more-312"></span>
<p>Typically, loading a pre-.NET 4 mixed mode assembly is handled simply by changing your app.Config file, and including the relevant attribute in the startup element:</p>
<pre class="csharpcode"><span class="kwrd">&lt;?</span><span class="html">xml</span> <span class="attr">version</span><span class="kwrd">=&quot;1.0&quot;</span> <span class="attr">encoding</span><span class="kwrd">=&quot;utf-8&quot;</span> ?<span class="kwrd">&gt;</span>
<span class="kwrd">&lt;</span><span class="html">configuration</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">startup</span> <span class="attr">useLegacyV2RuntimeActivationPolicy</span><span class="kwrd">=&quot;true&quot;</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">supportedRuntime</span> <span class="attr">version</span><span class="kwrd">=&quot;v4.0&quot;</span><span class="kwrd">/&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">startup</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">configuration</span><span class="kwrd">&gt;</span></pre>
<style type="text/css">
.csharpcode {
	background-color: #ffffff; font-family: consolas, "Courier New", courier, monospace; color: black; font-size: small
}
.csharpcode pre {
	background-color: #ffffff; font-family: consolas, "Courier New", courier, monospace; color: black; font-size: small
}
.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; margin: 0em; width: 100%
}
.csharpcode .lnum {
	color: #606060
}</style>
<p>This causes your application to run correctly, and load the older, mixed-mode assembly without issues. For full details on what’s happening here and why, I recommend reading <a href="http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx">Mark Miller’s detailed explanation</a> of this attribute and the reasoning behind it.</p>
<p>Before I show any code, let me say: </p>
<ul>
<li><strong>I strongly recommend using the official approach of using app.config to set this policy.</strong></li>
</ul>
<p>That being said, there are (rare) times when, for one reason or another, changing the application configuration file is less than ideal.</p>
<p>While this is the supported approach to handling this issue, the CLR Hosting API includes a means of setting this programmatically via the <a href="http://msdn.microsoft.com/en-us/library/dd233121.aspx">ICLRRuntimeInfo</a> interface.&#160; Normally, this is used if you’re hosting the CLR in a native application in order to set this, at runtime, prior to loading the assemblies.&#160; However, the F# Samples include a nice <a href="http://code.msdn.microsoft.com/3DVisualization-Visual-79471042/sourcecode?fileId=18993&amp;pathId=995930383">trick showing how to load this API and bind this policy</a>, at runtime.&#160; This was required in order to host the Managed DirectX API, which is built against an older version of the CLR.</p>
<p>This is fairly easy to port to C#.&#160; Instead of a direct port, I also added a little addition – by trapping the COM exception received if unable to bind (which will occur if the 2.0 CLR is already bound), I also allow a runtime check of whether this property was setup properly:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> RuntimePolicyHelper
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> LegacyV2RuntimeEnabledSuccessfully { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">static</span> RuntimePolicyHelper()
    {
        ICLRRuntimeInfo clrRuntimeInfo =
            (ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
                Guid.Empty, 
                <span class="kwrd">typeof</span>(ICLRRuntimeInfo).GUID);
        <span class="kwrd">try</span>
        {
            clrRuntimeInfo.BindAsLegacyV2Runtime();
            LegacyV2RuntimeEnabledSuccessfully = <span class="kwrd">true</span>;
        }
        <span class="kwrd">catch</span> (COMException)
        {
            <span class="rem">// This occurs with an HRESULT meaning </span>
            <span class="rem">// &quot;A different runtime was already bound to the legacy CLR version 2 activation policy.&quot;</span>
            LegacyV2RuntimeEnabledSuccessfully = <span class="kwrd">false</span>;
        }
    }

    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid(<span class="str">&quot;BD39D1D2-BA2F-486A-89B0-B4B0CB466891&quot;</span>)]
    <span class="kwrd">private</span> <span class="kwrd">interface</span> ICLRRuntimeInfo
    {
        <span class="kwrd">void</span> xGetVersionString();
        <span class="kwrd">void</span> xGetRuntimeDirectory();
        <span class="kwrd">void</span> xIsLoaded();
        <span class="kwrd">void</span> xIsLoadable();
        <span class="kwrd">void</span> xLoadErrorString();
        <span class="kwrd">void</span> xLoadLibrary();
        <span class="kwrd">void</span> xGetProcAddress();
        <span class="kwrd">void</span> xGetInterface();
        <span class="kwrd">void</span> xSetDefaultStartupFlags();
        <span class="kwrd">void</span> xGetDefaultStartupFlags();

        [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
        <span class="kwrd">void</span> BindAsLegacyV2Runtime();
    }
}</pre>
<p>Using this, it’s possible to not only set this at runtime, but also verify, prior to loading your mixed mode assembly, whether this will succeed.</p>
<p>In my case, this was quite useful – I am working on a library <em>purely for internal use </em>which uses a numerical package that is supplied with both a completely managed as well as a native solver.&#160; The native solver uses a CLR 2 mixed-mode assembly, but is dramatically faster than the pure managed approach.&#160; By checking RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully at runtime, I can decide whether to enable the native solver, and only do so if I successfully bound this policy.</p>
<p>There are some tricks required here – To enable this sort of fallback behavior, you must make these checks in a type that doesn’t cause the mixed mode assembly to be loaded.&#160; In my case, this forced me to encapsulate the library I was using entirely in a separate class, perform the check, then pass through the required calls to that class.&#160; Otherwise, the library will load before the hosting process gets enabled, which in turn will fail.</p>
<p>This code will also, of course, try to enable the runtime policy before the first time you use this class – which typically means just before the first time you check the boolean value.&#160; As a result, checking this early on in the application is more likely to allow it to work.</p>
<p>Finally, if you’re using a library, this has to be called prior to the 2.0 CLR loading.&#160; This will cause it to fail if you try to use it to enable this policy in a plugin for most third party applications that don’t have their app.config setup properly, as they will likely have already loaded the 2.0 runtime.</p>
<p>As an example, take a simple audio player.&#160; The code below shows how this can be used to properly, at runtime, only use the “native” API if this will succeed, and fallback (or raise a nicer exception) if this will fail:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> AudioPlayer
{
    <span class="kwrd">private</span> IAudioEngine audioEngine;

    <span class="kwrd">public</span> AudioPlayer()
    {
        <span class="kwrd">if</span> (RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully)
        {
            <span class="rem">// This will load a CLR 2 mixed mode assembly</span>
            <span class="kwrd">this</span>.audioEngine = <span class="kwrd">new</span> AudioEngineNative();
        }
        <span class="kwrd">else</span>
        {
            <span class="kwrd">this</span>.audioEngine = <span class="kwrd">new</span> AudioEngineManaged();
        }
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Play(<span class="kwrd">string</span> filename)
    {
        <span class="kwrd">this</span>.audioEngine.Play(filename);
    }
}</pre>
<p>Now – the warning:</p>
<p>This approach works, but I would be very hesitant to use it in public facing production code, especially for anything other than initializing your own application.&#160; While this should work in a library, using it has a very nasty side effect: you change the runtime policy of the executing application in a way that is very hidden and non-obvious.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/sgwC4sP-EAs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2011/09/15/setting-uselegacyv2runtimeactivationpolicy-at-runtime/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2011/09/15/setting-uselegacyv2runtimeactivationpolicy-at-runtime/</feedburner:origLink></item>
		<item>
		<title>Performance and Optimization Isn’t Evil</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/T4eUZitfr54/</link>
		<comments>http://reedcopsey.com/2011/09/09/performance-and-optimization-isnt-evil/#comments</comments>
		<pubDate>Sat, 10 Sep 2011 00:51:00 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Optimization]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2011/09/09/performance-and-optimization-isnt-evil/</guid>
		<description><![CDATA[Donald Knuth is a fairly amazing guy.&#160; I consider him one of the most influential contributors to computer science of all time.&#160; Unfortunately, most of the time I hear his name, I cringe.&#160; This is because it’s typically somebody quoting a small portion of one of his famous statements on optimization: “premature optimization is the [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Donald_Knuth">Donald Knuth</a> is a fairly amazing guy.&#160; I consider him one of the most influential contributors to computer science of all time.&#160; Unfortunately, most of the time I hear his name, I cringe.&#160; This is because it’s typically somebody quoting a small <em>portion</em> of one of his famous statements on optimization: “<em>premature optimization is the root of all evil.</em>”</p>
<p> I mention that this is only a <em>portion of the entire quote</em>, and, as such, I feel that Knuth is being quoted out of context.&#160; Optimization is important.&#160; It is a critical part of every software development effort, and should never be ignored.&#160; A developer who ignores optimization is not a professional.&#160; Every developer should understand optimization – know what to optimize, when to optimize it, and how to think about code in a way that is intelligent and productive from day one.<span id="more-311"></span>
<p align="left">I want to start by discussing my own, personal motivation here.&#160; I recently <a href="http://reedcopsey.com/2011/08/11/c-performance-pitfall-interop-scenarios-change-the-rules/">wrote about a performance issue I ran across</a>, and was slammed by multiple comments and emails that effectively boiled down to: “You’re an idiot.&#160; Premature optimization is the root of all evil.&#160; This doesn’t matter.”&#160; It didn’t matter that I discovered this <em>while measuring in a profiler</em>, and that it was a portion of my code base that can take “many hours to complete.”&#160; Even so, multiple people instantly jump to “it’s premature – it doesn’t matter.”</p>
<p>This is a common thread I see.&#160; For example, StackOverflow has <a href="http://stackoverflow.com/search?q=%22premature+optimization%22">many pages of posts</a> with answers that boil down to (mis)quoting Knuth.&#160; In fact, just about any question relating to a performance related issue gets this quote thrown at it immediately – whether it deserves it or not.&#160; </p>
<p>That being said, I did receive some positive comments and emails as well.&#160; Many people want to understand how to optimize their code, approaches to take, tools and techniques they can use, and any other advice they can discover.</p>
<p>First, lets get back to Knuth – I mentioned before that Knuth is being quoted out of context.&#160; Lets start by looking at the entire quote from his 1974 paper <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.103.6084&amp;rep=rep1&amp;type=pdf">Structured Programming with go to Statements</a>:</p>
<p>“<i>We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified.”</i></p>
<p>Ironically, if you read Knuth’s original paper, this statement was made in the middle of a discussion of how Knuth himself had changed how he approaches optimization.&#160; It was never a statement saying “don’t optimize”, but rather, “optimizing intelligently provides huge advantages.”&#160; His approach had three benefits: “<em>a) it doesn’t take long</em>” … <em>“b) the payoff is real”, </em>c) you can “<em>be less efficient in the other parts of my programs, which therefore are more readable and more easily written and debugged.”</em></p>
<p>Looking at Knuth’s premise here, and reading that section of his paper, really leads to a few observations:</p>
<ul>
<li>Optimization is important&#160; <em>“he will be wise to look carefully at the critical code”</em></li>
<li>Normally, 3% of your code – three lines out of every 100 you write, are “<em>critical code” </em>and will require some optimization: <em>“we should not pass up our opportunities in that critical 3%”</em></li>
<li>Optimization, if done well, should not be time consuming: “<em>it doesn’t take long</em>”</li>
<li>Optimization, if done correctly, provides real benefits: <em>“the payoff is real”</em></li>
</ul>
<p align="left">None of this is new information.&#160; People who care about optimization have been discussing this for years – for example, Rico Mariani’s <a href="http://blogs.msdn.com/b/ricom/archive/2003/12/12/43245.aspx">Designing For Performance</a> (a fantastic article) discusses many of the same issues very intelligently.</p>
<p align="left">That being said, many developers seem unable or unwilling to consider optimization.&#160; Many others don’t seem to know where to start.&#160; As such, I’m going to spend some time writing about optimization – what is it, how should we think about it, and what can we do to improve our own code.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/T4eUZitfr54" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2011/09/09/performance-and-optimization-isnt-evil/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2011/09/09/performance-and-optimization-isnt-evil/</feedburner:origLink></item>
		<item>
		<title>C# Performance Pitfall – Interop Scenarios Change the Rules</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/Kqz5lzcY2Zw/</link>
		<comments>http://reedcopsey.com/2011/08/11/c-performance-pitfall-interop-scenarios-change-the-rules/#comments</comments>
		<pubDate>Thu, 11 Aug 2011 19:30:52 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2011/08/11/c-performance-pitfall-interop-scenarios-change-the-rules/</guid>
		<description><![CDATA[C# and .NET, overall, really do have fantastic performance in my opinion.&#160; That being said, the performance characteristics dramatically differ from native programming, and take some relearning if you’re used to doing performance optimization in most other languages, especially C, C++, and similar.&#160; However, there are times when revisiting tricks learned in native code play [...]]]></description>
				<content:encoded><![CDATA[<p>C# and .NET, overall, really do have fantastic performance in my opinion.&#160; That being said, the performance characteristics dramatically differ from native programming, and take some relearning if you’re used to doing performance optimization in most other languages, especially C, C++, and similar.&#160; However, there are times when revisiting tricks learned in native code play a critical role in performance optimization in C#.</p>
<p>I recently ran across a nasty scenario that illustrated to me how dangerous following any fixed rules for optimization can be…</p>
<p><span id="more-310"></span>
<p>The rules in C# when optimizing code are very different than C or C++.&#160; Often, they’re exactly backwards.&#160; For example, in C and C++, lifting a variable out of loops in order to avoid memory allocations often can have huge advantages.&#160; If some function within a call graph is allocating memory dynamically, and that gets called in a loop, it can dramatically slow down a routine.</p>
<p>This can be a tricky bottleneck to track down, even with a profiler.&#160; Looking at the memory allocation graph is usually the key for spotting this routine, as it’s often “hidden” deep in call graph.&#160; For example, while optimizing some of my scientific routines, I ran into a situation where I had a loop similar to:</p>
<pre class="csharpcode"><span class="kwrd">for</span> (i=0; i&lt;numberToProcess; ++i)
{
   <span class="rem">// Do some work</span>
   ProcessElement(element[i]);
}</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 loop was at a fairly high level in the call graph, and often could take many <em>hours</em> to complete, depending on the input data.&#160; As such, any performance optimization we could achieve would be greatly appreciated by our users.</p>
<p>After a fair bit of profiling, I noticed that a couple of function calls down the call graph (inside of ProcessElement), there was some code that effectively was doing:</p>
<pre class="csharpcode"><span class="rem">// Allocate some data required</span>
DataStructure* data = <span class="kwrd">new</span> DataStructure(num);
<span class="rem">// Call into a subroutine that passed around and manipulated this data highly</span>
CallSubroutine(data);
<span class="rem">// Read and use some values from here</span>
<span class="kwrd">double</span> values = data-&gt;Foo;
<span class="rem">// Cleanup </span>
<span class="kwrd">delete</span> data;
<span class="rem">// ...</span>
<span class="kwrd">return</span> bar;</pre>
<p>Normally, if “DataStructure” was a simple data type, I could just allocate it on the stack.&#160; However, it’s constructor, internally, allocated it’s own memory using new, so this wouldn’t eliminate the problem.&#160; In this case, however, I could change the call signatures to allow the pointer to the data structure to be passed into ProcessElement and through the call graph, allowing the inner routine to <em>reuse</em> the same “data” memory instead of allocating.&#160; At the highest level, my code effectively changed to something like:</p>
<pre class="csharpcode">DataStructure* data = <span class="kwrd">new</span> DataStructure(numberToProcess);
<span class="kwrd">for</span> (i=0; i&lt;numberToProcess; ++i)
{
   <span class="rem">// Do some work</span>
   ProcessElement(element[i], data);
}
delete data;</pre>
<p>Granted, this dramatically reduced the maintainability of the code, so it wasn’t something I wanted to do unless there was a significant benefit.&#160; In this case, after profiling the new version, I found that it increased the overall performance dramatically – my main test case went from 35 minutes runtime down to 21 minutes.&#160; This was such a significant improvement, I felt it was worth the reduction in maintainability.</p>
<p>In C and C++, it’s generally a good idea (for performance) to:</p>
<ul>
<li>Reduce the number of memory allocations as much as possible, </li>
<li>Use fewer, larger memory allocations instead of many smaller ones, and </li>
<li>Allocate as high up the call stack as possible, and reuse memory </li>
</ul>
<p>I’ve seen many people try to make similar optimizations in C# code.&#160; For good or bad, this is typically <strong>not a good idea</strong>.&#160; The garbage collector in .NET completely changes the rules here.</p>
<p>In C#, reallocating memory in a loop is not always a bad idea.&#160; In this scenario, for example, I may have been much better off leaving the original code alone.&#160; The reason for this is the garbage collector.&#160; The GC in .NET is incredibly effective, and leaving the allocation deep inside the call stack has some huge advantages.&#160; First and foremost, it tends to make the code more maintainable – passing around object references tends to couple the methods together more than necessary, and overall increase the complexity of the code.&#160; This is something that should be avoided unless there is a significant reason.&#160; Second, (unlike C and C++) memory allocation of a single object in C# is normally cheap and fast.&#160; Finally, and most critically, there is a large advantage to having short lived objects.&#160; If you lift a variable out of the loop and reuse the memory, its much more likely that object will get promoted to Gen1 (or worse, Gen2).&#160; This can cause expensive compaction operations to be required, and also lead to (at least temporary) memory fragmentation as well as more costly collections later.</p>
<p>As such, I’ve found that it’s often (though not always) faster to leave memory allocations where you’d naturally place them – deep inside of the call graph, inside of the loops.&#160; This causes the objects to stay very short lived, which in turn increases the efficiency of the garbage collector, and can dramatically improve the overall performance of the routine as a whole.</p>
<p>In C#, I tend to:</p>
<ul>
<li>Keep variable declarations in the tightest scope possible</li>
<li>Declare and allocate objects at usage</li>
</ul>
<p>While this tends to cause some of the same goals (reducing unnecessary allocations, etc), the goal here is a bit different – it’s about keeping the objects rooted for as little time as possible in order to (attempt) to keep them completely in Gen0, or worst case, Gen1.&#160; It also has the huge advantage of keeping the code very maintainable – objects are used and “released” as soon as possible, which keeps the code very clean.&#160; It does, however, often have the side effect of causing more allocations to occur, but keeping the objects rooted for a much shorter time.</p>
<p>Now – nowhere here am I suggesting that these rules are hard, fast rules that are always true.&#160; That being said, my time spent optimizing over the years encourages me to naturally write code that follows the above guidelines, then profile and adjust as necessary.&#160; In my current project, however, I ran across one of those nasty little pitfalls that’s something to keep in mind – interop changes the rules.</p>
<p>In this case, I was dealing with an API that, internally, used some COM objects.&#160; In this case, these COM objects were leading to native allocations (most likely C++) occurring in a loop deep in my call graph.&#160; Even though I was writing nice, clean managed code, the normal managed code rules for performance no longer apply.&#160; </p>
<p>After profiling to find the bottleneck in my code, I realized that my inner loop, a innocuous looking block of C# code, was effectively causing a set of native memory allocations in every iteration.&#160; This required going back to a “native programming” mindset for optimization.&#160; Lifting these variables and reusing them took a 1:10 routine down to 0:20 – again, a very worthwhile improvement.</p>
<p>Overall, the lessons here are:</p>
<ul>
<li>Always profile if you suspect a performance problem – don’t assume any rule is correct, or any code is efficient just because it looks like it should be</li>
<li>Remember to check memory allocations when profiling, not just CPU cycles</li>
<li>Interop scenarios often cause managed code to act very differently than “normal” managed code.</li>
<li>Native code can be hidden very cleverly inside of managed wrappers</li>
</ul>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/Kqz5lzcY2Zw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2011/08/11/c-performance-pitfall-interop-scenarios-change-the-rules/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2011/08/11/c-performance-pitfall-interop-scenarios-change-the-rules/</feedburner:origLink></item>
		<item>
		<title>Async CTP Refresh for Visual Studio 2010 SP1 Released</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/4lLceWK0XdU/</link>
		<comments>http://reedcopsey.com/2011/04/13/async-ctp-refresh-for-visual-studio-2010-sp1-released/#comments</comments>
		<pubDate>Wed, 13 Apr 2011 16:30:29 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Async]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>
		<category><![CDATA[C# 5]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2011/04/13/async-ctp-refresh-for-visual-studio-2010-sp1-released/</guid>
		<description><![CDATA[The Visual Studio team today released an update to the Visual Studio Async CTP which allows it to be used with Visual Studio SP1.&#160; This new CTP includes some very nice new additions over the previous CTP.&#160; The main highlights of this release include: Compatibility with Visual Studio SP1 APIs for Windows Phone 7 Compatibility [...]]]></description>
				<content:encoded><![CDATA[<p>The Visual Studio team today released an <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=4738205d-5682-47bf-b62e-641f6441735b&amp;displaylang=en">update to the Visual Studio Async CTP</a> which allows it to be used with Visual Studio SP1.&#160; This new CTP includes some very nice new additions over the previous CTP.&#160; The main highlights of this release include:</p>
<ul>
<li>Compatibility with Visual Studio SP1</li>
<li>APIs for Windows Phone 7</li>
<li>Compatibility with non-English installations</li>
<li>Compatibility with Visual Studio Express Edition</li>
<li>More efficient Async methods due to a change in the API</li>
<li>Numerous bug fixes</li>
<li>New EULA which allows distribution in production environments</li>
<p> Anybody using the Async CTP should consider upgrading to the new version immediately.&#160; For details, visit the <a href="http://msdn.microsoft.com/en-us/vstudio/gg316360">Visual Studio Asynchronous Programming</a> page on MSDN.</ul>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/4lLceWK0XdU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2011/04/13/async-ctp-refresh-for-visual-studio-2010-sp1-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2011/04/13/async-ctp-refresh-for-visual-studio-2010-sp1-released/</feedburner:origLink></item>
		<item>
		<title>ConcurrentDictionary&lt;TKey,TValue&gt; used with Lazy&lt;T&gt;</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/PmMvJsNpJ0M/</link>
		<comments>http://reedcopsey.com/2011/01/16/concurrentdictionarytkeytvalue-used-with-lazyt/#comments</comments>
		<pubDate>Sun, 16 Jan 2011 21:04: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>

		<guid isPermaLink="false">http://reedcopsey.com/2011/01/16/concurrentdictionarytkeytvalue-used-with-lazyt/</guid>
		<description><![CDATA[In a recent thread on the MSDN forum for the TPL, Stephen Toub suggested mixing ConcurrentDictionary&#60;T,U&#62; with Lazy&#60;T&#62;.&#160; This provides a fantastic model for creating a thread safe dictionary of values where the construction of the value type is expensive.&#160; This is an incredibly useful pattern for many operations, such as value caches. The ConcurrentDictionary&#60;TKey, [...]]]></description>
				<content:encoded><![CDATA[<p>In a <a href="http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/e350f7d0-b860-482e-9b84-8dba12267d25">recent thread</a> on the <a href="http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/threads">MSDN forum for the TPL</a>, Stephen Toub suggested mixing ConcurrentDictionary&lt;T,U&gt; with Lazy&lt;T&gt;.&#160; This provides a fantastic model for creating a thread safe dictionary of values where the construction of the value type is expensive.&#160; This is an incredibly useful pattern for many operations, such as value caches.</p>
<p>  <span id="more-295"></span>
<p>The <a href="http://msdn.microsoft.com/en-us/library/dd287191.aspx">ConcurrentDictionary&lt;TKey, TValue&gt; class</a> was added in .NET 4, and provides a thread-safe, lock free collection of key value pairs.&#160; While this is a fantastic replacement for Dictionary&lt;TKey, TValue&gt;, it has a potential flaw when used with values where construction of the value class is expensive.</p>
<p>The typical way this is used is to call a method such as <a href="http://msdn.microsoft.com/en-us/library/ee378677.aspx">GetOrAdd</a> to fetch or add a value to the dictionary.&#160; It handles all of the thread safety for you, but as a result, if two threads call this simultaneously, two instances of TValue can easily be constructed.</p>
<p>If TValue is very expensive to construct, or worse, has side effects if constructed too often, this is less than desirable.&#160; While you can easily work around this with locking, Stephen Toub provided a very clever alternative – using Lazy&lt;TValue&gt; as the value in the dictionary instead.</p>
<p>This looks like the following.&#160; Instead of calling:</p>
<pre class="csharpcode">MyValue <span class="kwrd">value</span> = dictionary.GetOrAdd(
                             key, 
                             () =&gt; <span class="kwrd">new</span> MyValue(key));</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 instead use a ConcurrentDictionary&lt;TKey, Lazy&lt;TValue&gt;&gt;, and write:</p>
<pre class="csharpcode">MyValue <span class="kwrd">value</span> = dictionary.GetOrAdd(
                             key, 
                             () =&gt; <span class="kwrd">new</span> Lazy&lt;MyValue&gt;(
                                 () =&gt; <span class="kwrd">new</span> MyValue(key)))
                          .Value;</pre>
<p>This simple change dramatically changes how the operation works.&#160; Now, if two threads call this simultaneously, instead of constructing two MyValue instances, we construct two Lazy&lt;MyValue&gt; instances.</p>
<p>However, the Lazy&lt;T&gt; class is very cheap to construct.&#160; Unlike “MyValue”, we can safely afford to construct this twice and “throw away” one of the instances.</p>
<p>We then call Lazy&lt;T&gt;.Value at the end to fetch our “MyValue” instance.&#160; At this point, GetOrAdd will always return the same instance of Lazy&lt;MyValue&gt;.&#160; Since Lazy&lt;T&gt; doesn’t construct the MyValue instance until requested, the actual MyClass instance returned is only constructed once.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/PmMvJsNpJ0M" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2011/01/16/concurrentdictionarytkeytvalue-used-with-lazyt/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2011/01/16/concurrentdictionarytkeytvalue-used-with-lazyt/</feedburner:origLink></item>
		<item>
		<title>C# 5 Async, Part 3: Preparing Existing code For Await</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/eUoiPcmskAw/</link>
		<comments>http://reedcopsey.com/2010/12/14/c-5-async-part-3-preparing-existing-code-for-await/#comments</comments>
		<pubDate>Tue, 14 Dec 2010 18:25:00 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Async]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET 4.5]]></category>
		<category><![CDATA[C# 5]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/12/14/c-5-async-part-3-preparing-existing-code-for-await/</guid>
		<description><![CDATA[While the Visual Studio Async CTP provides a fantastic model for asynchronous programming, it requires code to be implemented in terms of Task and Task&#60;T&#62;.&#160; The CTP adds support for Task-based asynchrony to the .NET Framework methods, and promises to have these implemented directly in the framework in the future.&#160; However, existing code outside the [...]]]></description>
				<content:encoded><![CDATA[<p>While the <a href="http://msdn.microsoft.com/en-gb/vstudio/async.aspx" target="_blank">Visual Studio Async CTP</a> provides a fantastic model for asynchronous programming, it requires code to be implemented in terms of <a href="http://msdn.microsoft.com/en-us/library/dd537609.aspx">Task and Task&lt;T&gt;</a>.&#160; The CTP adds support for Task-based asynchrony to the .NET Framework methods, and promises to have these implemented directly in the framework in the future.&#160; However, existing code outside the framework will need to be converted to using the Task class prior to being usable via the CTP.</p>
<p>  <span id="more-292"></span> Wrapping existing asynchronous code into a Task or Task&lt;T&gt; is, thankfully, fairly straightforward.&#160; There are two main approaches to this.
<p>Code written using the <a href="http://msdn.microsoft.com/en-us/library/ms228963.aspx">Asynchronous Programming Model</a> (APM) is very easy to convert to using Task&lt;T&gt;.&#160; The <a href="http://msdn.microsoft.com/en-us/library/dd321401.aspx">TaskFactory class</a> provides the tools to directly convert APM code into a method returning a Task&lt;T&gt;.&#160; This is done via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.fromasync.aspx">FromAsync method</a>.&#160; This method takes the BeginOperation and EndOperation methods, as well as any parameters and state objects as arguments, and returns a Task&lt;T&gt; directly.</p>
<p>For example, we could easily convert the WebRequest BeginGetResponse and EndGetResponse methods into a method which returns a Task&lt;WebResponse&gt; via:</p>
<pre class="csharpcode">Task&lt;WebResponse&gt; task = Task.Factory
                             .FromAsync&lt;WebResponse&gt;(
                                 request.BeginGetResponse,
                                 request.EndGetResponse,
                                 <span class="kwrd">null</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><!--.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; } --><a href="http://msdn.microsoft.com/en-us/library/wewwczdw.aspx">Event-based Asynchronous Pattern</a> (EAP) code can also be wrapped into a Task&lt;T&gt;, though this requires a bit more effort than the one line of code above.&#160; This is handled via the <a href="http://msdn.microsoft.com/en-us/library/dd449174.aspx">TaskCompletionSource&lt;T&gt; class</a>.&#160; MSDN provides a detailed <a href="http://msdn.microsoft.com/en-us/library/ee622454.aspx">example of using this to wrap an EAP operation into a method returning Task&lt;T&gt;</a>.&#160; It demonstrates handling cancellation and exception handling as well as the basic operation of the asynchronous method itself.</p>
<p>The basic form of this operation is typically:</p>
<pre class="csharpcode">Task&lt;YourResult&gt; GetResultAsync()
{
    var tcs = <span class="kwrd">new</span> TaskCompletionSource&lt;YourResult&gt;();
    <span class="rem">// Handle the event, and setup the task results...</span>
    <span class="kwrd">this</span>.GetResultCompleted += (o,e) =&gt;
    {
       <span class="kwrd">if</span> (e.Error != <span class="kwrd">null</span>)
            tcs.TrySetException(e.Error);
       <span class="kwrd">else</span> <span class="kwrd">if</span> (e.Cancelled)
            tcs.TrySetCanceled();
       <span class="kwrd">else</span>
            tcs.TrySetResult(e.Result);
    };

    <span class="rem">// Call the EAP-based asynchronous method</span>
    <span class="kwrd">this</span>.GetResult();

    <span class="rem">// Return the task from the TaskCompletionSource</span>
    <span class="kwrd">return</span> tcs.Task;
}</pre>
<p>We can easily use these methods to wrap our own code into a method that returns a Task&lt;T&gt;.&#160; Existing libraries which cannot be edited can be extended via Extension methods.&#160; The CTP uses this technique to add appropriate methods throughout the framework.</p>
<p>The suggested naming for these methods is to define these methods as “Task&lt;YourResult&gt; YourClass.YourOperation<strong>Async</strong>(…)”.&#160; However, this naming often conflicts with the default naming of the EAP.&#160; If this is the case, the CTP has standardized on using “Task&lt;YourResult&gt; YourClass.YourOperation<strong>TaskAsync</strong>(…)”.</p>
<p>Once we’ve wrapped all of our existing code into operations that return Task&lt;T&gt;, we can begin investigating how the Async CTP can be used with our own code.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/eUoiPcmskAw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/12/14/c-5-async-part-3-preparing-existing-code-for-await/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/12/14/c-5-async-part-3-preparing-existing-code-for-await/</feedburner:origLink></item>
		<item>
		<title>C# 5 Async, Part 2: Asynchrony Today</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/uLTJaDkAHqQ/</link>
		<comments>http://reedcopsey.com/2010/12/02/c-5-async-part-2-asynchrony-today/#comments</comments>
		<pubDate>Thu, 02 Dec 2010 23:44:00 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Async]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET 4.5]]></category>
		<category><![CDATA[C# 5]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/12/02/c-5-async-part-2-asynchrony-today/</guid>
		<description><![CDATA[The .NET Framework has always supported asynchronous operations.&#160; However, different mechanisms for supporting exist throughout the framework.&#160; While there are at least three separate asynchronous patterns used through the framework, only the latest is directly usable with the new Visual Studio Async CTP.&#160; Before delving into details on the new features, I will talk about [...]]]></description>
				<content:encoded><![CDATA[<p>The .NET Framework has always supported asynchronous operations.&#160; However, different mechanisms for supporting exist throughout the framework.&#160; While there are at least three separate asynchronous patterns used through the framework, only the latest is directly usable with the new <a href="http://msdn.microsoft.com/en-gb/vstudio/async.aspx" target="_blank">Visual Studio Async CTP</a>.&#160; Before delving into details on the new features, I will talk about existing asynchronous code, and demonstrate how to adapt it for use with the new pattern.</p>
<p>  <span id="more-291"></span>
<p align="left">The first asynchronous pattern used in the .NET framework was the <a href="http://msdn.microsoft.com/en-us/library/ms228963.aspx">Asynchronous Programming Model</a> (APM).&#160; This pattern was based around <a href="http://en.wikipedia.org/wiki/Callback_(computer_science)">callbacks</a>.&#160; A method is used to start the operation.&#160; It typically is named as <strong>Begin</strong>SomeOperation.&#160; This method is passed a callback defined as an <a href="http://msdn.microsoft.com/en-us/library/system.asynccallback.aspx">AsyncCallback</a>, and returns an object that implements <a href="http://msdn.microsoft.com/en-us/library/system.iasyncresult.aspx">IAsyncResult</a>.&#160; Later, the IAsyncResult is used in a call to a method named <strong>End</strong>SomeOperation, which blocks until completion and returns the value normally directly returned from the synchronous version of the operation.&#160; Often, the <strong>End</strong>SomeOperation call would be called from the callback function passed, which allows you to write code that never blocks.</p>
<p align="left">While this pattern works perfectly to prevent blocking, it can make quite confusing code, and be difficult to implement.&#160; For example, the sample code provided for <a href="http://msdn.microsoft.com/en-us/library/7db28s3c.aspx">FileStream’s BeginRead/EndRead</a> methods is not simple to understand.&#160; In addition, implementing your own asynchronous methods requires creating an entire class just to implement the IAsyncResult.</p>
<p align="left">Given the complexity of the APM, other options have been introduced in later versions of the framework.&#160; The next major pattern introduced was the <a href="http://msdn.microsoft.com/en-us/library/wewwczdw.aspx">Event-based Asynchronous Pattern</a> (EAP).&#160; This provides a simpler pattern for asynchronous operations.&#160; It works by providing a method typically named SomeOperation<strong>Async</strong>, which signals its completion via an event typically named SomeOperation<strong>Completed</strong>.</p>
<p align="left">The EAP provides a simpler model for asynchronous programming.&#160; It is much easier to understand and use, and far simpler to implement.&#160; Instead of requiring a custom class and callbacks, the standard event mechanism in C# is used directly.&#160; For example, the <a href="http://msdn.microsoft.com/en-us/library/tt0f69eh.aspx">WebClient class</a> uses this extensively.&#160; A method is used, such as <a href="http://msdn.microsoft.com/en-us/library/ms144190.aspx">DownloadDataAsync</a>, and the results are returned via the <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient.downloaddatacompleted.aspx">DownloadDataCompleted</a> event.</p>
<p align="left">While the EAP is far simpler to understand and use than the APM, it is still not ideal.&#160; By separating your code into method calls and event handlers, the logic of your program gets more complex.&#160; It also typically loses the ability to block until the result is received, which is often useful.&#160; Blocking often requires writing the code to block by hand, which is error prone and adds complexity.</p>
<p align="left">As a result, .NET 4 introduced a third major pattern for asynchronous programming.&#160; The <a href="http://reedcopsey.com/2010/03/15/parallelism-in-net-part-13-introducing-the-task-class/">Task&lt;T&gt; class</a> introduced a new, simpler concept for asynchrony.&#160; Task and Task&lt;T&gt; effectively represent an operation that will complete at some point in the future.&#160; This is a perfect model for thinking about asynchronous code, and is the preferred model for all new code going forward.&#160; Task and Task&lt;T&gt; provide all of the advantages of both the APM and the EAP models – you have the ability to block on results (via Task.Wait() or Task&lt;T&gt;.Result), and you can stay completely asynchronous via the use of <a href="http://reedcopsey.com/2010/04/19/parallelism-in-net-part-17-think-continuations-not-callbacks/">Task Continuations</a>.&#160; In addition, the Task class provides a new model for <a href="http://reedcopsey.com/2010/07/19/parallelism-in-net-part-18-task-continuations-with-multiple-tasks/">task composition</a> and <a href="http://reedcopsey.com/2010/10/26/parallelism-in-net-part-19-taskcontinuationoptions/">error and cancelation handling</a>.&#160; This is a far superior option to the previous asynchronous patterns.</p>
<p align="left">The <a href="http://msdn.microsoft.com/en-gb/vstudio/async.aspx" target="_blank">Visual Studio Async CTP</a> extends the Task based asynchronous model, allowing it to be used in a much simpler manner.&#160; However, it requires the use of Task and Task&lt;T&gt; for all operations.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/uLTJaDkAHqQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/12/02/c-5-async-part-2-asynchrony-today/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/12/02/c-5-async-part-2-asynchrony-today/</feedburner:origLink></item>
		<item>
		<title>C# 5 Async, Part 1: Simplifying Asynchrony – That for which we await</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/shyjKQ9zfU8/</link>
		<comments>http://reedcopsey.com/2010/10/28/c-5-async-part-1-simplifying-asynchrony-that-for-which-we-await/#comments</comments>
		<pubDate>Thu, 28 Oct 2010 18:46:47 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Async]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[.NET 4.5]]></category>
		<category><![CDATA[C# 5]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/10/28/c-5-async-part-1-simplifying-asynchrony-that-for-which-we-await/</guid>
		<description><![CDATA[Today’s announcement at PDC of the future directions C# is taking excite me greatly.&#160; The new Visual Studio Async CTP is amazing.&#160; Asynchronous code – code which frustrates and demoralizes even the most advanced of developers, is taking a huge leap forward in terms of usability.&#160; This is handled by building on the Task functionality [...]]]></description>
				<content:encoded><![CDATA[<p>Today’s announcement at PDC of the future directions C# is taking excite me greatly.&#160; The new <a href="http://msdn.microsoft.com/en-gb/vstudio/async.aspx" target="_blank">Visual Studio Async CTP</a> is amazing.&#160; Asynchronous code – code which frustrates and demoralizes even the most advanced of developers, is taking a huge leap forward in terms of usability.&#160; This is handled by building on the <a href="http://reedcopsey.com/2010/03/15/parallelism-in-net-part-13-introducing-the-task-class/" target="_blank">Task</a> functionality in .NET 4, as well as the addition of two new keywords being added to the C# language: <strong>async </strong>and <strong>await</strong>.</p>
<p>    <span id="more-289"></span>
<p align="left">This core of the new asynchronous functionality is built upon three key features.&#160; First is the <a href="http://reedcopsey.com/2010/03/15/parallelism-in-net-part-13-introducing-the-task-class/" target="_blank">Task functionality</a> in .NET 4, and based on <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx" target="_blank">Task</a> and <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx" target="_blank">Task&lt;TResult&gt;</a>.&#160; While Task was intended to be the <a href="http://msdn.microsoft.com/en-us/library/dd537609.aspx" target="_blank">primary means of asynchronous programming</a> with .NET 4, the .NET Framework was still based mainly on the <a href="http://msdn.microsoft.com/en-us/library/ms228969.aspx" target="_blank">Asynchronous Pattern and the Event-based Asynchronous Pattern</a>.</p>
<p align="left">The .NET Framework added functionality and guidance for <a href="http://msdn.microsoft.com/en-us/library/dd997405.aspx" target="_blank">wrapping existing APIs into a Task based API</a>, but the framework itself didn’t really adopt Task or Task&lt;TResult&gt; in any meaningful way.&#160; The CTP shows that, going forward, this is changing.</p>
<p align="left">One of the three key new features coming in C# is actually a .NET Framework feature.&#160; Nearly every asynchronous API in the .NET Framework has been wrapped into a new, Task-based method calls.&#160; In the CTP, this is done via as external assembly (<em>AsyncCtpLibrary.dll</em>) which uses Extension Methods to wrap the existing APIs.&#160; However, going forward, this will be handled directly within the Framework.&#160; This will have a unifying effect throughout the .NET Framework.&#160; This is the first building block of the new features for asynchronous programming:</p>
<p align="left"><strong>Going forward, all asynchronous operations will work via a method that returns Task or Task&lt;TResult&gt;</strong></p>
<p align="left">The second key feature is the new <strong>async</strong> contextual keyword being added to the language.&#160; The <strong>async </strong>keyword is used to declare an <em>asynchronous function</em>, which is a method that either returns void, a Task, or a Task&lt;T&gt;.</p>
<p>Inside the asynchronous function, there must be at least one <strong>await </strong>expression.&#160; This is a new C# keyword (<strong>await</strong>) that is used to automatically take a series of statements and break it up to potentially use discontinuous evaluation.&#160; This is done by using <strong>await </strong>on any expression that evaluates to a <strong>Task</strong> or <strong>Task&lt;T&gt;</strong>.</p>
<p>For example, suppose we want to download a webpage as a string.&#160; There is a new method added to <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx" target="_blank">WebClient</a>: Task&lt;string&gt; WebClient.DownloadStringTaskAsync(Uri).&#160; Since this returns a Task&lt;string&gt; we can use it within an asynchronous function.&#160; Suppose, for example, that we wanted to do something similar to <a href="http://reedcopsey.com/2010/10/27/parallelism-in-net-part-20-using-task-with-existing-apis/" target="_blank">my asynchronous Task example</a> – download a web page asynchronously and check to see if it supports XHTML 1.0, then report this into a TextBox.&#160; This could be done like so:</p>
<pre class="csharpcode"><span class="kwrd">private</span> async <span class="kwrd">void</span> button1_Click(<span class="kwrd">object</span> sender, RoutedEventArgs e)
{
    <span class="kwrd">string</span> url = <span class="str">&quot;http://reedcopsey.com&quot;</span>;
    <span class="kwrd">string</span> content = await <span class="kwrd">new</span> WebClient().DownloadStringTaskAsync(url);
    <span class="kwrd">this</span>.textBox1.Text = <span class="kwrd">string</span>.Format(<span class="str">&quot;Page {0} supports XHTML 1.0: {1}&quot;</span>,
      url, content.Contains(<span class="str">&quot;XHTML 1.0&quot;</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>Let’s walk through what’s happening here, step by step.&#160; By adding the <strong>async </strong>contextual keyword to the method definition, we are able to use the <strong>await </strong>keyword on our WebClient.DownloadStringTaskAsync method call.</p>
<p>When the user clicks this button, the new method (Task&lt;string&gt; WebClient.DownloadStringTaskAsync(string)) is called, which returns a Task&lt;string&gt;.&#160; By adding the <strong>await</strong> keyword, the runtime will call this method that returns Task&lt;string&gt;, and execution will return to the caller at this point.&#160; This means that our <strong>UI is not blocked while the webpage is downloaded.</strong>&#160; Instead, the UI thread will “await” at this point, and let the WebClient do it’s thing asynchronously.</p>
<p>When the WebClient finishes downloading the string, the user interface’s synchronization context will automatically be used to “pick up” where it left off, and the Task&lt;string&gt; returned from DownloadStringTaskAsync is automatically unwrapped and set into the content variable.&#160; At this point, we can use that and set our text box content.</p>
<p>There are a couple of key points here:</p>
<p><strong>Asynchronous functions are declared with the <em>async </em>keyword, and contain one or more <em>await </em>expressions</strong></p>
<p>In addition to the obvious benefits of shorter, simpler code – there are some subtle but tremendous benefits in this approach.&#160; When the execution of this asynchronous function continues after the first await statement, the initial synchronization context is used to continue the execution of this function.&#160; That means that <strong>we don’t have to explicitly marshal the call that sets textbox1.Text back to the UI thread – </strong>it’s handled automatically by the language and framework!&#160; Exception handling around asynchronous method calls also just works.</p>
<p>I’d recommend every C# developer take a look at the documentation on the new <a href="http://msdn.microsoft.com/en-gb/vstudio/async.aspx" target="_blank">Asynchronous Programming for C# and Visual Basic</a> page, download the <a href="http://go.microsoft.com/fwlink/?LinkId=203690" target="_blank">Visual Studio Async CTP</a>, and try it out.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/shyjKQ9zfU8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/10/28/c-5-async-part-1-simplifying-asynchrony-that-for-which-we-await/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/10/28/c-5-async-part-1-simplifying-asynchrony-that-for-which-we-await/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 20, Using Task with Existing APIs</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/aXzRIlEr5QQ/</link>
		<comments>http://reedcopsey.com/2010/10/27/parallelism-in-net-part-20-using-task-with-existing-apis/#comments</comments>
		<pubDate>Wed, 27 Oct 2010 20:15: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/10/27/parallelism-in-net-part-20-using-task-with-existing-apis/</guid>
		<description><![CDATA[Although the Task class provides a huge amount of flexibility for handling asynchronous actions, the .NET Framework still contains a large number of APIs that are based on the previous asynchronous programming model.&#160; While Task and Task&#60;T&#62; provide a much nicer syntax as well as extending the flexibility, allowing features such as continuations based on [...]]]></description>
				<content:encoded><![CDATA[<p align="left">Although the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx">Task class</a> provides a huge amount of flexibility for handling asynchronous actions, the .NET Framework still contains a large number of APIs that are based on the previous <a href="http://msdn.microsoft.com/en-us/library/ms228963.aspx">asynchronous programming model</a>.&#160; While Task and Task&lt;T&gt; provide a much nicer syntax as well as extending the flexibility, allowing features such as <a href="http://reedcopsey.com/2010/07/19/parallelism-in-net-part-18-task-continuations-with-multiple-tasks/">continuations based on multiple tasks</a>, the existing APIs don’t directly support this workflow. </p>
<p>  <span id="more-288"></span>
<p align="left">There is a method in the <a href="http://msdn.microsoft.com/en-us/library/dd321401.aspx">TaskFactory class</a> which can be used to adapt the existing APIs to the new Task class: <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.fromasync(v=VS.100).aspx">TaskFactory.FromAsync</a>.&#160; This method provides a way to convert from the BeginOperation/EndOperation method pair syntax common through .NET Framework directly to a Task&lt;T&gt; containing the results of the operation in the task’s Result parameter.</p>
<p align="left">While this method does exist, it unfortunately comes at a cost – the method overloads are far from simple to decipher, and the resulting code is not always as easily understood as newer code based directly on the Task class.&#160; For example, a single call to handle WebRequest.BeginGetResponse/EndGetReponse, one of the easiest “pairs” of methods to use, looks like the following:</p>
<pre class="csharpcode">var task = Task.Factory.FromAsync&lt;WebResponse&gt;(
                            request.BeginGetResponse,
                            request.EndGetResponse,
                            <span class="kwrd">null</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>The compiler is unfortunately unable to infer the correct type, and, as a result, the WebReponse must be explicitly mentioned in the method call.&#160; As a result, I typically recommend wrapping this into an extension method to ease use.&#160; For example, I would place the above in an extension method like:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> WebRequestExtensions
{
    <span class="kwrd">public</span> <span class="kwrd">static</span> Task&lt;WebResponse&gt; GetReponseAsync(<span class="kwrd">this</span> WebRequest request)
    {
        <span class="kwrd">return</span> Task.Factory.FromAsync&lt;WebResponse&gt;(
                        request.BeginGetResponse,
                        request.EndGetResponse,
                        <span class="kwrd">null</span>);
    }
}</pre>
<p>This dramatically simplifies usage.&#160; For example, if we wanted to asynchronously check to see if this blog supported XHTML 1.0, and report that in a text box to the user, we could do:</p>
<pre class="csharpcode">var webRequest = WebRequest.Create(<span class="str">&quot;http://www.reedcopsey.com&quot;</span>);
webRequest.GetReponseAsync().ContinueWith(t =&gt;
    {
        <span class="kwrd">using</span> (var sr = <span class="kwrd">new</span> StreamReader(t.Result.GetResponseStream()))
        {
            <span class="kwrd">string</span> str = sr.ReadLine();;
            <span class="kwrd">this</span>.textBox1.Text = <span class="kwrd">string</span>.Format(<span class="str">&quot;Page at {0} supports XHTML 1.0: {1}&quot;</span>, 
                t.Result.ResponseUri, 
                str.Contains(<span class="str">&quot;XHTML 1.0&quot;</span>));
        }
    }, TaskScheduler.FromCurrentSynchronizationContext());</pre>
<p>&#160;</p>
<p>By using a continuation with a TaskScheduler based on the current synchronization context, we can keep this request asynchronous, check based on the first line of the response string, and report the results back on our UI directly.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/aXzRIlEr5QQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/10/27/parallelism-in-net-part-20-using-task-with-existing-apis/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/10/27/parallelism-in-net-part-20-using-task-with-existing-apis/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 19, TaskContinuationOptions</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/pxcv_l65Wks/</link>
		<comments>http://reedcopsey.com/2010/10/26/parallelism-in-net-part-19-taskcontinuationoptions/#comments</comments>
		<pubDate>Wed, 27 Oct 2010 00:30:53 +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/10/26/parallelism-in-net-part-19-taskcontinuationoptions/</guid>
		<description><![CDATA[My introduction to Task continuations demonstrates continuations on the Task class.&#160; In addition, I’ve shown how continuations allow handling of multiple tasks in a clean, concise manner.&#160; Continuations can also be used to handle exceptional situations using a clean, simple syntax. In addition to standard Task continuations , the Task class provides some options for [...]]]></description>
				<content:encoded><![CDATA[<p align="left">My <a href="http://reedcopsey.com/2010/04/19/parallelism-in-net-part-17-think-continuations-not-callbacks/" target="_blank">introduction to Task continuations</a> demonstrates continuations on the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx" target="_blank">Task class</a>.&#160; In addition, I’ve shown how <a href="http://reedcopsey.com/2010/07/19/parallelism-in-net-part-18-task-continuations-with-multiple-tasks/" target="_blank">continuations allow handling of multiple tasks</a> in a clean, concise manner.&#160; Continuations can also be used to handle exceptional situations using a clean, simple syntax.</p>
<p>  <span id="more-284"></span>
<p align="left">In addition to standard <a href="http://reedcopsey.com/2010/04/19/parallelism-in-net-part-17-think-continuations-not-callbacks/" target="_blank">Task continuations</a> , the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx" target="_blank">Task class</a> provides some options for filtering continuations automatically.&#160; This is handled via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskcontinuationoptions.aspx" target="_blank">TaskContinationOptions</a> enumeration, which provides hints to the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.aspx" target="_blank">TaskScheduler</a> that it should only continue based on the operation of the antecedent task.</p>
<p align="left">This is especially useful when dealing with exceptions.&#160; For example, we can extend <a href="http://reedcopsey.com/2010/04/19/parallelism-in-net-part-17-think-continuations-not-callbacks/" target="_blank">the sample from our earlier continuation discussion</a> to include support for handling exceptions thrown by the Factorize method:</p>
<pre class="csharpcode"><span class="rem">// Get a copy of the UI-thread task scheduler up front to use later</span>
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

<span class="rem">// Start our task</span>
var factorize = Task.Factory.StartNew(
    () =&gt;
        {
            <span class="kwrd">int</span> primeFactor1 = 0;
            <span class="kwrd">int</span> primeFactor2 = 0;
            <span class="kwrd">bool</span> result = Factorize(10298312, <span class="kwrd">ref</span> primeFactor1, <span class="kwrd">ref</span> primeFactor2);
            <span class="kwrd">return</span> <span class="kwrd">new</span> {
                           Result = result,
                           Factor1 = primeFactor1,
                           Factor2 = primeFactor2
                       };
        });

<span class="rem">// When we succeed, report the results to the UI</span>
factorize.ContinueWith(task =&gt; textBox1.Text = <span class="kwrd">string</span>.Format(<span class="str">&quot;{0}/{1}  [Succeeded {2}]&quot;</span>,
                                 task.Result.Factor1,
                                 task.Result.Factor2,
                                 task.Result.Result),
                        CancellationToken.None,
                        TaskContinuationOptions.NotOnFaulted,
                        uiScheduler);

<span class="rem">// When we have an exception, report it</span>
factorize.ContinueWith(task =&gt; 
                             textBox1.Text = <span class="kwrd">string</span>.Format(<span class="str">&quot;Error: {0}&quot;</span>, task.Exception.Message),
                        CancellationToken.None,
                        TaskContinuationOptions.OnlyOnFaulted,
                        uiScheduler);</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>The above code works by using a combination of features.&#160; First, we schedule our task, the same way as in <a href="http://reedcopsey.com/2010/04/19/parallelism-in-net-part-17-think-continuations-not-callbacks/" target="_blank">the previous example</a>.&#160; However, in this case, we use a different overload of <a href="http://msdn.microsoft.com/en-us/library/dd991174.aspx" target="_blank">Task.ContinueWith</a> which allows us to specify both a specific TaskScheduler (in order to have your continuation run on the UI’s synchronization context) as well as a <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskcontinuationoptions.aspx" target="_blank">TaskContinuationOption</a>.&#160; </p>
<p>In the first continuation, we tell the continuation that we only want it to run when there was not an exception by specifying <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskcontinuationoptions.aspx" target="_blank">TaskContinuationOptions.NotOnFaulted</a>.&#160; When our factorize task completes successfully, this continuation will automatically run on the UI thread, and provide the appropriate feedback.</p>
<p>However, if the factorize task has an exception – for example, if the Factorize method throws an exception due to an improper input value, the second continuation will run.&#160; This occurs due to the specification of <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskcontinuationoptions.aspx" target="_blank">TaskContinuationOptions.OnlyOnFaulted</a> in the options.&#160; In this case, we’ll report the error received to the user.</p>
<p>We can use <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskcontinuationoptions.aspx" target="_blank">TaskContinuationOptions</a> to filter our continuations by whether or not an exception occurred and whether or not a task was cancelled.&#160; This allows us to handle many situations, and is especially useful when trying to maintain a valid application state without ever blocking the user interface.&#160; The same concepts can be extended even further, and allow you to chain together many tasks based on the success of the previous ones.&#160; Continuations can even be used to <a href="http://blogs.msdn.com/b/pfxteam/archive/2010/02/09/9960735.aspx" target="_blank">create a state machine</a> with full error handling, all without blocking the user interface thread.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/pxcv_l65Wks" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/10/26/parallelism-in-net-part-19-taskcontinuationoptions/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/10/26/parallelism-in-net-part-19-taskcontinuationoptions/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 18, Task Continuations with Multiple Tasks</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/Uxg3GSnESYU/</link>
		<comments>http://reedcopsey.com/2010/07/19/parallelism-in-net-part-18-task-continuations-with-multiple-tasks/#comments</comments>
		<pubDate>Tue, 20 Jul 2010 01:18: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/07/19/parallelism-in-net-part-18-task-continuations-with-multiple-tasks/</guid>
		<description><![CDATA[In my introduction to Task continuations I demonstrated how the Task class provides a more expressive alternative to traditional callbacks.&#160; Task continuations provide a much cleaner syntax to traditional callbacks, but there are other reasons to switch to using continuations… Task continuations provide a clean syntax, and a very simple, elegant means of synchronizing asynchronous [...]]]></description>
				<content:encoded><![CDATA[<p>In my <a href="http://reedcopsey.com/2010/04/19/parallelism-in-net-part-17-think-continuations-not-callbacks/" target="_blank">introduction to Task continuations</a> I demonstrated how the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx" target="_blank">Task class</a> provides a more expressive alternative to <a href="http://en.wikipedia.org/wiki/Callback_(computer_science)" target="_blank">traditional callbacks</a>.&#160; <a href="http://msdn.microsoft.com/en-us/library/ee372288.aspx" target="_blank">Task continuations</a> provide a much cleaner syntax to traditional callbacks, but there are other reasons to switch to using continuations…</p>
<p> <span id="more-282"></span>
<p><a href="http://msdn.microsoft.com/en-us/library/ee372288.aspx" target="_blank">Task continuations</a> provide a clean syntax, and a very simple, elegant means of synchronizing asynchronous method results with the user interface.&#160; In addition, continuations provide a very simple, elegant means of working with collections of tasks.</p>
<p>Prior to .NET 4, working with multiple related asynchronous method calls was very tricky.&#160; If, for example, we wanted to run two asynchronous operations, followed by a single method call which we wanted to run when the first two methods completed, we’d have to program all of the handling ourselves.&#160; We would likely need to take some approach such as using a shared callback which synchronized against a common variable, or using a <a href="http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx" target="_blank">WaitHandle</a> shared within the callbacks to allow one to wait for the second.&#160; Although this could be accomplished easily enough, it requires manually placing this handling into every algorithm which requires this form of blocking.&#160; This is error prone, difficult, and can easily lead to subtle bugs.</p>
<p>Similar to how the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx" target="_blank">Task class</a> static methods providing a way to <a href="http://reedcopsey.com/2010/03/15/parallelism-in-net-part-13-introducing-the-task-class/" target="_blank">block until multiple tasks have completed</a>, <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.aspx" target="_blank">TaskFactory</a> contains static methods which allow a continuation to be scheduled upon the completion of multiple tasks: <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.continuewhenall.aspx" target="_blank">TaskFactory.ContinueWhenAll</a>.</p>
<p>This allows you to easily specify a single delegate to run when a collection of tasks has completed.&#160; For example, suppose we have a class which fetches data from the network.&#160; This can be a long running operation, and potentially fail in certain situations, such as a server being down.&#160; As a result, we have three separate servers which we will “query” for our information.&#160; Now, suppose we want to grab data from all three servers, and verify that the results are the same from all three.</p>
<p>With traditional asynchronous programming in .NET, this would require using three separate callbacks, and managing the synchronization between the various operations ourselves.&#160; The <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx" target="_blank">Task</a> and <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.aspx" target="_blank">TaskFactory</a> classes simplify this for us, allowing us to write:</p>
<pre class="csharpcode">var server1 = Task.Factory.StartNew( 
                 () =&gt; networkClass.GetResults(firstServer) );
var server2 = Task.Factory.StartNew( 
                 () =&gt; networkClass.GetResults(secondServer) );
var server3 = Task.Factory.StartNew( 
                 () =&gt; networkClass.GetResults(thirdServer) );

var result = Task.Factory.ContinueWhenAll( <span class="kwrd">new</span>[] {server1, server2, server3 },
                 (tasks) =&gt; 
                 {
                       <span class="rem">// Propogate exceptions (see below)</span>
                       Task.WaitAll(tasks);

                       return <span class="kwrd">this</span>.CompareTaskResults(
                               tasks[0].Result,
                               tasks[1].Result,
                               tasks[2].Result);
                  });</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>This is clean, simple, and elegant.&#160; The one complication is the Task.WaitAll(tasks); statement.</p>
<p>Although the continuation will not complete until all three tasks (server1, server2, and server3) have completed, there is a potential snag.&#160; If the networkClass.GetResults method fails, and raises an exception, we want to make sure to handle it cleanly.&#160; By using Task.WaitAll, any exceptions raised within any of our original tasks will get wrapped into a single <a href="http://msdn.microsoft.com/en-us/library/system.aggregateexception.aspx" target="_blank">AggregateException</a> by the <a href="http://msdn.microsoft.com/en-us/library/dd270695.aspx" target="_blank">WaitAll</a> method, providing us a simplified means of handling the exceptions.&#160; If we wait on the continuation, we can trap this <a href="http://msdn.microsoft.com/en-us/library/system.aggregateexception.aspx" target="_blank">AggregateException</a>, and handle it cleanly.&#160; Without this line, it’s possible that an exception could remain uncaught and <em>unhandled </em>by a task, which later might trigger a nasty <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.unobservedtaskexception.aspx" target="_blank">UnobservedTaskException</a>.&#160; This would happen any time two of our original tasks failed.</p>
<p>Just as we can schedule a continuation to occur when an entire collection of tasks has completed, we can just as easily setup a continuation to run when any single task within a collection completes.&#160; If, for example, we didn’t need to compare the results of all three network locations, but only use one, we could still schedule three tasks.&#160; We could then have our completion logic work on the first task which completed, and ignore the others.&#160; This is done via <a href="http://msdn.microsoft.com/en-us/library/dd321530.aspx" target="_blank">TaskFactory.ContinueWhenAny</a>:</p>
<pre class="csharpcode">var server1 = Task.Factory.StartNew( 
                 () =&gt; networkClass.GetResults(firstServer) );
var server2 = Task.Factory.StartNew( 
                 () =&gt; networkClass.GetResults(secondServer) );
var server3 = Task.Factory.StartNew( 
                 () =&gt; networkClass.GetResults(thirdServer) );

var result = Task.Factory.ContinueWhenAny( <span class="kwrd">new</span>[] {server1, server2, server3 },
                 (firstTask) =&gt; 
                 {
                       <span class="kwrd">return</span> <span class="kwrd">this</span>.ProcessTaskResult(firstTask.Result);
                  });</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, instead of working with all three tasks, we’re just using the first task which finishes.&#160; This is very useful, as it allows us to easily work with results of multiple operations, and “throw away” the others.&#160; However, you must take care when using <a href="http://msdn.microsoft.com/en-us/library/dd321530.aspx" target="_blank">ContinueWhenAny</a> to properly handle exceptions.&#160; At some point, you should always wait on each task (or use the Task.Result property) in order to propogate any exceptions raised from within the task.&#160; Failing to do so can lead to an <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.unobservedtaskexception.aspx" target="_blank">UnobservedTaskException</a>.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/Uxg3GSnESYU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/07/19/parallelism-in-net-part-18-task-continuations-with-multiple-tasks/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/07/19/parallelism-in-net-part-18-task-continuations-with-multiple-tasks/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 17, Think Continuations, not Callbacks</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/0udITkKwnkE/</link>
		<comments>http://reedcopsey.com/2010/04/19/parallelism-in-net-part-17-think-continuations-not-callbacks/#comments</comments>
		<pubDate>Mon, 19 Apr 2010 20:27:40 +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[Windows Forms]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/04/19/parallelism-in-net-part-17-think-continuations-not-callbacks/</guid>
		<description><![CDATA[In traditional asynchronous programming, we’d often use a callback to handle notification of a background task’s completion.&#160; The Task class in the Task Parallel Library introduces a cleaner alternative to the traditional callback: continuation tasks. Asynchronous programming methods typically required callback functions.&#160; For example, MSDN’s Asynchronous Delegates Programming Sample shows a class that factorizes a [...]]]></description>
				<content:encoded><![CDATA[<p>In traditional asynchronous programming, we’d often use a <a href="http://en.wikipedia.org/wiki/Callback_(computer_science)" target="_blank">callback</a> to handle notification of a background task’s completion.&#160; The <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a> in the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> introduces a cleaner alternative to the traditional <a href="http://en.wikipedia.org/wiki/Callback_(computer_science)" target="_blank">callback</a>: <a href="http://msdn.microsoft.com/en-us/library/ee372288.aspx" target="_blank">continuation tasks</a>.</p>
<p> <span id="more-272"></span>
<p>Asynchronous programming methods typically required callback functions.&#160; For example, MSDN’s <a href="http://msdn.microsoft.com/en-us/library/h80ttd5f(VS.90).aspx" target="_blank">Asynchronous Delegates Programming Sample</a> shows a class that factorizes a number.&#160; The original method in the example has the following signature:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> Factorize(<span class="kwrd">int</span> number, <span class="kwrd">ref</span> <span class="kwrd">int</span> primefactor1, <span class="kwrd">ref</span> <span class="kwrd">int</span> primefactor2)
{
 //...</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>However, calling this is quite “tricky”, even if we modernize the sample to use lambda expressions via C# 3.0.&#160; </p>
<p>Normally, we could call this method like so:</p>
<pre class="csharpcode"><span class="kwrd">int</span> primeFactor1 = 0;
<span class="kwrd">int</span> primeFactor2 = 0;

<span class="kwrd">bool</span> answer = Factorize(10298312, <span class="kwrd">ref</span> primeFactor1, <span class="kwrd">ref</span> primeFactor2);
Console.WriteLine(<span class="str">&quot;{0}/{1}  [Succeeded {2}]&quot;</span>, primeFactor1, primeFactor2, answer);</pre>
<p>If we want to make this operation run in the background, and report to the console via a callback, things get tricker.&#160; First, we need a delegate definition: </p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">delegate</span> <span class="kwrd">bool</span> AsyncFactorCaller(
     <span class="kwrd">int</span> number,
     <span class="kwrd">ref</span> <span class="kwrd">int</span> primefactor1,
     <span class="kwrd">ref</span> <span class="kwrd">int</span> primefactor2);</pre>
<p>Then we need to use BeginInvoke to run this method asynchronously:</p>
<pre class="csharpcode"><span class="kwrd">int</span> primeFactor1 = 0;
<span class="kwrd">int</span> primeFactor2 = 0;

AsyncFactorCaller caller  = <span class="kwrd">new</span> AsyncFactorCaller(Factorize);
caller.BeginInvoke(10298312, <span class="kwrd">ref</span> primeFactor1, <span class="kwrd">ref</span> primeFactor2,
   result =&gt;
       {
           <span class="kwrd">int</span> factor1 = 0;
           <span class="kwrd">int</span> factor2 = 0;
           <span class="kwrd">bool</span> answer = caller.EndInvoke(<span class="kwrd">ref</span> factor1, <span class="kwrd">ref</span> factor2, result);
           Console.WriteLine(<span class="str">&quot;{0}/{1}  [Succeeded {2}]&quot;</span>, factor1, factor2, answer);
       }, <span class="kwrd">null</span>);</pre>
<p>This works, but is quite difficult to understand from a conceptual standpoint.&#160; To combat this, the framework added the <a href="http://msdn.microsoft.com/en-us/library/wewwczdw(VS.90).aspx" target="_blank">Event-based Asynchronous Pattern</a>, but it isn’t much easier to understand or author. </p>
<p>Using .NET 4’s new Task&lt;T&gt; class and a continuation, we can dramatically simplify the implementation of the above code, as well as make it much more understandable.&#160; We do this via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.continuewith.aspx" target="_blank">Task.ContinueWith</a> method.&#160; This method will schedule a new Task upon completion of the original task, and provide the original Task (including its Result if it’s a <a href="http://msdn.microsoft.com/en-us/library/dd321424.aspx" target="_blank">Task&lt;T&gt;</a>) as an argument.&#160; Using Task, we can eliminate the delegate, and rewrite this code like so:</p>
<pre class="csharpcode">var background = Task.Factory.StartNew(
    () =&gt;
        {
            <span class="kwrd">int</span> primeFactor1 = 0;
            <span class="kwrd">int</span> primeFactor2 = 0;
            <span class="kwrd">bool</span> result = Factorize(10298312, <span class="kwrd">ref</span> primeFactor1, <span class="kwrd">ref</span> primeFactor2);
            <span class="kwrd">return</span> <span class="kwrd">new </span>{
                           Result = result,
                           Factor1 = primeFactor1,
                           Factor2 = primeFactor2
                       };
        });
background.ContinueWith(task =&gt; Console.WriteLine(<span class="str">&quot;{0}/{1}  [Succeeded {2}]&quot;</span>,
                                 task.Result.Factor1,
                                 task.Result.Factor2,
                                 task.Result.Result));</pre>
<p>This is much simpler to understand, in my opinion.&#160; Here, we’re explicitly asking to start a new task, then <strong>continue</strong> the task with a resulting task.&#160; In our case, our method used ref parameters (this was from the MSDN Sample), so there is a little bit of extra boiler plate involved, but the code is at least easy to understand.</p>
<p>That being said, this isn’t dramatically shorter when compared with our C# 3 port of the MSDN code above.&#160; However, if we were to extend our requirements a bit, we can start to see more advantages to the Task based approach.&#160; For example, supposed we need to report the results in a user interface control instead of reporting it to the Console.&#160; This would be a common operation, but now, we have to think about marshaling our calls back to the user interface.&#160; This is probably going to require calling Control.Invoke or Dispatcher.Invoke within our callback, forcing us to specify a delegate within the delegate.&#160; The maintainability and ease of understanding drops.&#160; However, just as a standard <a href="http://reedcopsey.com/2010/03/18/parallelism-in-net-part-15-making-tasks-run-the-taskscheduler/" target="_blank">Task can be created with a TaskScheduler that uses the UI synchronization context</a>, so too can we continue a task with a specific context.&#160; There are <a href="http://msdn.microsoft.com/en-us/library/dd321307.aspx" target="_blank">Task.ContinueWith method overloads</a> which allow you to provide a <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.aspx" target="_blank">TaskScheduler</a>.&#160; This means you can schedule the continuation to run on the UI thread, by simply doing:</p>
<pre class="csharpcode">Task.Factory.StartNew(
    () =&gt;
        {
            <span class="kwrd">int</span> primeFactor1 = 0;
            <span class="kwrd">int</span> primeFactor2 = 0;
            <span class="kwrd">bool</span> result = Factorize(10298312, <span class="kwrd">ref</span> primeFactor1, <span class="kwrd">ref</span> primeFactor2);
            <span class="kwrd">return</span> <span class="kwrd">new</span> {
                           Result = result,
                           Factor1 = primeFactor1,
                           Factor2 = primeFactor2
                       };
        }).ContinueWith(task =&gt; textBox1.Text = <span class="kwrd">string</span>.Format(<span class="str">&quot;{0}/{1}  [Succeeded {2}]&quot;</span>,
                                 task.Result.Factor1,
                                 task.Result.Factor2,
                                 task.Result.Result), 
                        TaskScheduler.FromCurrentSynchronizationContext());</pre>
<p>This is far more understandable than the alternative.&#160; By using <a href="http://msdn.microsoft.com/en-us/library/dd321307.aspx" target="_blank">Task.ContinueWith</a> in conjunction with <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.fromcurrentsynchronizationcontext.aspx" target="_blank">TaskScheduler.FromCurrentSynchronizationContext()</a>, we get a simple way to push any work onto a background thread, and update the user interface on the proper UI thread.&#160; This technique works with Windows Presentation Foundation as well as Windows Forms, with no change in methodology.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/0udITkKwnkE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/04/19/parallelism-in-net-part-17-think-continuations-not-callbacks/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/04/19/parallelism-in-net-part-17-think-continuations-not-callbacks/</feedburner:origLink></item>
		<item>
		<title>Attached Property port of my Window Close Behavior</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/xQdx1EuBNSI/</link>
		<comments>http://reedcopsey.com/2010/04/15/attached-property-port-of-my-window-close-behavior/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 21:12:39 +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/2010/04/15/attached-property-port-of-my-window-close-behavior/</guid>
		<description><![CDATA[Nishant Sivakumar just posted a nice article on The Code Project.&#160; It is a port of the MVVM-friendly Blend Behavior I wrote about in a previous article to WPF using Attached Properties. While similar to the WindowCloseBehavior code I posted on the Expression Code Gallery, Nishant Sivakumar’s version works in WPF without taking a dependency [...]]]></description>
				<content:encoded><![CDATA[<p><a href="http://blog.voidnish.com/" target="_blank">Nishant Sivakumar</a> just posted a nice article on <a href="http://www.codeproject.com/" target="_blank">The Code Project</a>.&#160; It is a port of the MVVM-friendly Blend Behavior I wrote about in <a href="http://reedcopsey.com/2009/10/09/using-behaviors-to-allow-the-viewmodel-to-manage-view-lifetime-in-m-v-vm/" target="_blank">a previous article</a> to WPF using <a href="http://msdn.microsoft.com/en-us/library/ms749011.aspx" target="_blank">Attached Properties</a>.</p>
<p>While similar to the <a href="http://gallery.expression.microsoft.com/en-us/WindowCloseBehavior" target="_blank">WindowCloseBehavior code I posted on the Expression Code Gallery</a>, <a href="http://www.codeproject.com/KB/WPF/WindowClosingBehavior.aspx" target="_blank">Nishant Sivakumar’s version</a> works in WPF without taking a dependency on the Expression Blend SDK.</p>
<p>I highly recommend reading this article: <a href="http://www.codeproject.com/KB/WPF/WindowClosingBehavior.aspx" target="_blank">Handling a Window’s Closed and Closing Events in the View-Model</a>.&#160; It is a very nice alternative approach to this common problem in MVVM.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/xQdx1EuBNSI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/04/15/attached-property-port-of-my-window-close-behavior/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/04/15/attached-property-port-of-my-window-close-behavior/</feedburner:origLink></item>
		<item>
		<title>2010 Visual C# MVP Award</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/LFWhRpuLxEQ/</link>
		<comments>http://reedcopsey.com/2010/04/01/2010-visual-c-mvp-award/#comments</comments>
		<pubDate>Thu, 01 Apr 2010 23:05:11 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Professional]]></category>
		<category><![CDATA[MVP]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/04/01/2010-visual-c-mvp-award/</guid>
		<description><![CDATA[I received a pleasant surprise today.&#160; I was presented this morning with the 2010 Microsoft® MVP Award for Visual C#.&#160; According to the award email, this “award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others.” I feel honored and proud to receive this award, and [...]]]></description>
				<content:encoded><![CDATA[<p>I received a pleasant surprise today.&#160; I was presented this morning with the <a href="https://mvp.support.microsoft.com/default.aspx/gp/mvpawardintro" target="_blank">2010 Microsoft® MVP Award</a> for Visual C#.&#160; According to the award email, this “award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others.”</p>
<p>I feel honored and proud to receive this award, and hope that I can continue to be a valuable member of the community in the future.&#160; Thank you to everyone who nominated me!</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/LFWhRpuLxEQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/04/01/2010-visual-c-mvp-award/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/04/01/2010-visual-c-mvp-award/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 16, Creating Tasks via a TaskFactory</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/q3WkRk1TRBQ/</link>
		<comments>http://reedcopsey.com/2010/03/26/parallelism-in-net-part-16-creating-tasks-via-a-taskfactory/#comments</comments>
		<pubDate>Sat, 27 Mar 2010 00:51:58 +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/26/parallelism-in-net-part-16-creating-tasks-via-a-taskfactory/</guid>
		<description><![CDATA[The Task class in the Task Parallel Library supplies a large set of features.&#160; However, when creating the task, and assigning it to a TaskScheduler, and starting the Task, there are quite a few steps involved.&#160; This gets even more cumbersome when multiple tasks are involved.&#160; Each task must be constructed, duplicating any options required, [...]]]></description>
				<content:encoded><![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a> in the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> supplies a large set of features.&#160; However, when <a href="http://reedcopsey.com/2010/03/17/parallelism-in-net-part-14-the-different-forms-of-task/" target="_blank">creating the task</a>, and <a href="http://reedcopsey.com/2010/03/18/parallelism-in-net-part-15-making-tasks-run-the-taskscheduler/" target="_blank">assigning it to a TaskScheduler</a>, and starting the <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a>, there are quite a few steps involved.&#160; This gets even more cumbersome when multiple tasks are involved.&#160; Each task must be constructed, duplicating any options required, then started individually, potentially on a specific scheduler.&#160; At first glance, this makes the new <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a> seem like more work than <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx" target="_blank">ThreadPool.QueueUserWorkItem</a> in .NET 3.5.</p>
<p>In order to simplify this process, and make Tasks simple to use in simple cases, without sacrificing their power and flexibility, the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> added a new class: <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory(VS.100).aspx" target="_blank">TaskFactory</a>.</p>
<p> <span id="more-263"></span>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory(VS.100).aspx" target="_blank">TaskFactory class</a> is intended to “Provide support for creating and scheduling Task objects.”&#160; Its entire purpose is to simplify development when working with <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> instances.&#160; The <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> class provides access to the default <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory(VS.100).aspx" target="_blank">TaskFactory</a> via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.factory(VS.100).aspx" target="_blank">Task.Factory</a> static property.&#160; By default, <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory(VS.100).aspx" target="_blank">TaskFactory</a> uses the <a href="http://reedcopsey.com/2010/03/18/parallelism-in-net-part-15-making-tasks-run-the-taskscheduler/" target="_blank">default TaskScheduler</a> to schedule tasks on a ThreadPool thread.&#160; By using Task.Factory, we can automatically create and start a task in a single “fire and forget” manner, similar to how we did with <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx" target="_blank">ThreadPool.QueueUserWorkItem</a>:</p>
<pre class="csharpcode">Task.Factory.StartNew(() =&gt; <span class="kwrd">this</span>.ExecuteBackgroundWork(myData) );</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>This provides us with the same level of simplicity we had with <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx" target="_blank">ThreadPool.QueueUserWorkItem</a>, but even more power.&#160; For example, we can now easily wait on the task:</p>
<pre class="csharpcode"><span class="rem">// Start our task on a background thread</span>
var task = Task.Factory.StartNew(() =&gt; <span class="kwrd">this</span>.ExecuteBackgroundWork(myData) );

<span class="rem">// Do other work on the main thread, </span>
<span class="rem">// while the task above executes in the background</span>
<span class="kwrd">this</span>.ExecuteWorkSynchronously();

<span class="rem">// Wait for the background task to finish</span>
task.Wait();</pre>
<p><a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory(VS.100).aspx" target="_blank">TaskFactory</a> simplifies creation and startup of simple background tasks dramatically.</p>
<p>In addition to using the default <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory(VS.100).aspx" target="_blank">TaskFactory</a>, it’s often useful to construct a custom <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory(VS.100).aspx" target="_blank">TaskFactory</a>.&#160; The <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory(VS.100).aspx" target="_blank">TaskFactory class</a> includes an entire <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.taskfactory(VS.100).aspx" target="_blank">set of constructors</a> which allow you to specify the default configuration for every <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> instance created by that factory.&#160; </p>
<p>This is particularly useful when <a href="http://reedcopsey.com/2010/03/18/parallelism-in-net-part-15-making-tasks-run-the-taskscheduler/" target="_blank">using a custom TaskScheduler</a>.&#160; For example, look at the <a href="http://reedcopsey.com/2010/03/18/parallelism-in-net-part-15-making-tasks-run-the-taskscheduler/" target="_blank">sample code for starting a task on the UI thread in Part 15</a>:</p>
<pre class="csharpcode"><span class="rem">// Given the following, constructed on the UI thread</span>
<span class="rem">// TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();</span>

<span class="rem">// When inside a background task, we can do</span>
<span class="kwrd">string</span> status = GetUpdatedStatus();

(<span class="kwrd">new</span> Task(() =&gt;
    {
        statusLabel.Text = status;
    }))
.Start(uiScheduler);</pre>
<p>This is actually quite a bit more complicated than necessary.&#160; When we create the <em>uiScheduler</em> instance, we can use that to construct a <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory(VS.100).aspx" target="_blank">TaskFactory</a> that will automatically schedule tasks on the UI thread.&#160; To do that, we’d create the following on our main thread, prior to constructing our background tasks:</p>
<pre class="csharpcode"><span class="rem">// Construct a task scheduler from the current SynchronizationContext (UI thread)</span>
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
<span class="rem">// Construct a new TaskFactory using our UI scheduler</span>
var uiTaskFactory = <span class="kwrd">new</span> TaskFactory(uiScheduler);</pre>
<p>If we do this, when we’re on a background thread, we can use this new <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory(VS.100).aspx" target="_blank">TaskFactory</a> to marshal a Task back onto the UI thread.&#160; Our previous code simplifies to:</p>
<pre class="csharpcode"><span class="rem">// When inside a background task, we can do</span>
<span class="kwrd">string</span> status = GetUpdatedStatus();

<span class="rem">// Update our UI</span>
uiTaskFactory.StartNew( () =&gt; statusLabel.Text = status);</pre>
<p>Notice how much simpler this becomes!&#160; By taking advantage of the convenience provided by a custom <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory(VS.100).aspx" target="_blank">TaskFactory</a>, we can now marshal to set data on the UI thread in a single, clear line of code!</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/q3WkRk1TRBQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/03/26/parallelism-in-net-part-16-creating-tasks-via-a-taskfactory/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/03/26/parallelism-in-net-part-16-creating-tasks-via-a-taskfactory/</feedburner:origLink></item>
		<item>
		<title>MEF CompositionInitializer for WPF</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/IldJ7GDQt08/</link>
		<comments>http://reedcopsey.com/2010/03/26/mef-compositioninitializer-for-wpf/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 22:45:46 +0000</pubDate>
		<dc:creator>Reed</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[.NET 4]]></category>
		<category><![CDATA[C# 4]]></category>
		<category><![CDATA[MEF]]></category>

		<guid isPermaLink="false">http://reedcopsey.com/2010/03/26/mef-compositioninitializer-for-wpf/</guid>
		<description><![CDATA[The Managed Extensibility Framework is an amazingly useful addition to the .NET Framework.  I was very excited to see System.ComponentModel.Composition added to the core framework.  Personally, I feel that MEF is one tool I’ve always been missing in my .NET development. Unfortunately, one perfect scenario for MEF tends to fall short of it’s full potential [...]]]></description>
				<content:encoded><![CDATA[<p>The <a href="http://mef.codeplex.com/" target="_blank">Managed Extensibility Framework</a> is an amazingly useful addition to the .NET Framework.  I was very excited to see <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition(VS.100).aspx" target="_blank">System.ComponentModel.Composition</a> added to the core framework.  Personally, I feel that MEF is one tool I’ve always been missing in my .NET development.</p>
<p>Unfortunately, one perfect scenario for MEF tends to fall short of it’s full potential is in <a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx" target="_blank">Windows Presentation Foundation</a> development.  In particular, there are many times when the XAML parser constructs objects in WPF development, which makes composition of those parts difficult.  The current release of MEF (Preview Release 9) addresses this for Silverlight developers via System.ComponentModel.Composition.CompositionInitializer.  However, there is no equivalent class for WPF developers.</p>
<p><span id="more-255"></span></p>
<p>The CompositionInitializer class provides the means for an object to compose itself.  This is very useful with WPF and Silverlight development, since it allows a View, such as a UserControl, to be generated via the standard XAML parser, and still automatically pull in the appropriate ViewModel in an extensible manner.  Glenn Block has demonstrated the <a href="http://blogs.msdn.com/gblock/archive/2010/03/08/building-hellomef-part-v-refactoring-to-viewmodel.aspx" target="_blank">usage for Silverlight in detail</a>, but the same issues apply in WPF.</p>
<p>As an example, let’s take a look at a very simple case.  Take the following XAML for a Window:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">Window</span> <span class="attr">x:Class</span><span class="kwrd">="WpfApplication1.MainView"</span>
        <span class="attr">xmlns</span><span class="kwrd">="http://schemas.microsoft.com/winfx/2006/xaml/presentation"</span>
        <span class="attr">xmlns:x</span><span class="kwrd">="http://schemas.microsoft.com/winfx/2006/xaml"</span>
        <span class="attr">Title</span><span class="kwrd">="MainWindow"</span> <span class="attr">Height</span><span class="kwrd">="220"</span> <span class="attr">Width</span><span class="kwrd">="300"</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">Grid</span><span class="kwrd">&gt;</span>
        <span class="kwrd">&lt;</span><span class="html">TextBlock</span> <span class="attr">Text</span><span class="kwrd">="{Binding TheText}"</span> <span class="kwrd">/&gt;</span>
    <span class="kwrd">&lt;/</span><span class="html">Grid</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">Window</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; } --> <!-- .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; } -->This does nothing but create a Window, add a simple TextBlock control, and use it to display the value of our “TheText” property in our DataContext class.  Since this is our main window, WPF will automatically construct and display this Window, so we need to handle constructing the DataContext and setting it ourselves.</p>
<p>We could do this in code or in XAML, but in order to do it directly, we would need to hard code the ViewModel type directly into our XAML code, or we would need to construct the ViewModel class and set it in the code behind.  Both have disadvantages, and the disadvantages grow if we’re using MEF to compose our ViewModel.</p>
<p>Ideally, we’d like to be able to have MEF construct our ViewModel for us.  This way, it can provide any construction requirements for our ViewModel via [ImportingConstructor], and it can handle fully composing the imported properties on our ViewModel.  CompositionInitializer allows this to occur.</p>
<p>We use CompositionInitializer within our View’s constructor, and use it for self-composition of our View.  Using CompositionInitializer, we can modify our code behind to:</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">partial</span> <span class="kwrd">class</span> MainView : Window
{
    <span class="kwrd">public</span> MainView()
    {
        InitializeComponent();
        CompositionInitializer.SatisfyImports(<span class="kwrd">this</span>);
    }

    [Import(<span class="str">"MainViewModel"</span>)]
    <span class="kwrd">public</span> <span class="kwrd">object</span> ViewModel
    {
        get { <span class="kwrd">return</span> <span class="kwrd">this</span>.DataContext; }
        set { <span class="kwrd">this</span>.DataContext = <span class="kwrd">value</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; } -->We then can add an Export on our ViewModel class like so:</p>
<pre class="csharpcode">[Export(<span class="str">"MainViewModel"</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> MainViewModel
{
    <span class="kwrd">public</span> <span class="kwrd">string</span> TheText
    {
        get
        {
            <span class="kwrd">return</span> <span class="str">"Hello World!"</span>;
        }
    }
}</pre>
<p>MEF will automatically compose our application, decoupling our ViewModel injection to the DataContext of our View until runtime.  When we run this, we’ll see:</p>
<p><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/03/MainWindow1.png"><img style="display: block; float: none; margin-left: auto; margin-right: auto; border: 0px;" title="MainWindow" src="http://reedcopsey.com/blog/wp-content/uploads/2010/03/MainWindow_thumb1.png" border="0" alt="MainWindow" width="300" height="220" /></a></p>
<p>There are many other approaches for using MEF to wire up the extensible parts within your application, of course.  However, any time an object is going to be constructed by code outside of your control, CompositionInitializer allows us to continue to use MEF to satisfy the import requirements of that object.</p>
<p>In order to use this from WPF, I’ve ported the code from <a href="http://mef.codeplex.com/releases/view/40606" target="_blank">MEF Preview 9</a> and <a href="http://cid-f8b2fd72406fb218.skydrive.live.com/self.aspx/blog/Composition.Initialization.Desktop.zip?sa=947050772" target="_blank">Glenn Block’s (now obsolete) PartInitializer port</a> to Windows Presentation Foundation.  There are some subtle changes from the Silverlight port, mainly to handle running in a desktop application context.  The default behavior of my port is to construct an <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.aggregatecatalog(VS.100).aspx" target="_blank">AggregateCatalog</a> containing a <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.directorycatalog(VS.100).aspx" target="_blank">DirectoryCatalog</a> set to the location of the entry assembly of the application.  In addition, if an “Extensions” folder exists under the entry assembly’s directory, a second <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.directorycatalog(VS.100).aspx" target="_blank">DirectoryCatalog</a> for that folder will be included.  This behavior can be overridden by specifying a <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.compositioncontainer(VS.100).aspx" target="_blank">CompositionContainer</a> or one or more <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.primitives.composablepartcatalog(VS.100).aspx" target="_blank">ComposablePartCatalogs</a> to the System.ComponentModel.Composition.Hosting.CompositionHost static class prior to the first use of CompositionInitializer.</p>
<p>Please download CompositionInitializer and CompositionHost for VS 2010 RC, and <a href="http://reedcopsey.com/contact-me/" target="_blank">contact me</a> with any feedback.</p>
<ul>
<li><strong><a href="http://reedcopsey.com/blog/wp-content/uploads/2010/03/Composition.Initialization.Desktop.zip" target="_blank">Composition.Initialization.Desktop.zip</a></strong></li>
</ul>
<h2>Edit on 3/29:</h2>
<p>Glenn Block has since updated his version of CompositionInitializer (and ExportFactory&lt;T&gt;!), and made it available here:</p>
<ul>
<li><a rel="nofollow" href="http://cid-f8b2fd72406fb218.skydrive.live.com/self.aspx/blog/Composition.Initialization.Desktop.zip">http://cid-f8b2fd72406fb218.skydrive.live.com/self.aspx/blog/Composition.Initialization.Desktop.zip</a></li>
</ul>
<p>This is a .NET 3.5 solution, and should soon be pushed to CodePlex, and made available on the main MEF site.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/IldJ7GDQt08" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/03/26/mef-compositioninitializer-for-wpf/feed/</wfw:commentRss>
		<slash:comments>32</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/03/26/mef-compositioninitializer-for-wpf/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 15, Making Tasks Run: The TaskScheduler</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/q4KzxNmFSI8/</link>
		<comments>http://reedcopsey.com/2010/03/18/parallelism-in-net-part-15-making-tasks-run-the-taskscheduler/#comments</comments>
		<pubDate>Fri, 19 Mar 2010 01:10: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/03/18/parallelism-in-net-part-15-making-tasks-run-the-taskscheduler/</guid>
		<description><![CDATA[In my introduction to the Task class, I specifically made mention that the Task class does not directly provide it’s own execution.&#160; In addition, I made a strong point that the Task class itself is not directly related to threads or multithreading.&#160; Rather, the Task class is used to implement our decomposition of tasks.&#160; Once [...]]]></description>
				<content:encoded><![CDATA[<p>In my <a href="http://reedcopsey.com/2010/03/15/parallelism-in-net-part-13-introducing-the-task-class/" target="_blank">introduction to the Task class</a>, I specifically made mention that the <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a> does not directly provide it’s own execution.&#160; In addition, I made a strong point that the <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a> itself is not directly related to threads or multithreading.&#160; Rather, the <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a> is used to implement our <a href="http://reedcopsey.com/2010/03/05/parallelism-in-net-part-12-more-on-task-decomposition/" target="_blank">decomposition of tasks</a>.&#160; </p>
<p>Once we’ve implemented our tasks, we need to execute them.&#160; In the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a>, the execution of <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Tasks</a> is handled via an instance of the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler class</a>.</p>
<p> <span id="more-249"></span>
<p>The <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler class</a> is an abstract class which provides a single function: it schedules the tasks and executes them within an appropriate context.&#160; This class is the class which actually runs individual <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> instances.&#160; The .NET Framework provides two (internal) implementations of the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler class</a>.</p>
<p>Since a <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a>, based on our <a href="http://reedcopsey.com/2010/03/05/parallelism-in-net-part-12-more-on-task-decomposition/" target="_blank">decomposition</a>, should be a self-contained piece of code, parallel execution makes sense when executing tasks.&#160; The default implementation of the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler class</a>, and the one most often used, is based on the <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx" target="_blank">ThreadPool</a>.&#160; This can be retrieved via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.default(v=VS.100).aspx" target="_blank">TaskScheduler.Default</a> property, and is, by default, what is used when we just start a <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> instance with <a href="http://msdn.microsoft.com/en-us/library/dd270682(v=VS.100).aspx" target="_blank">Task.Start()</a>.</p>
<p>Normally, when a <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> is started by the default <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler</a>, the task will be treated as a single work item, and run on a <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx" target="_blank">ThreadPool</a> thread.&#160; This pools tasks, and provides <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> instances all of the advantages of the <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx" target="_blank">ThreadPool</a>, including thread pooling for reduced resource usage, and an upper cap on the number of work items.&#160; In addition, <a href="http://www.developerfusion.com/media/31201/erika-parsons-and-eric-eilebrecht-clr-4-inside-the-thread-pool/" target="_blank">.NET 4 brings us a much improved thread pool</a>, providing work stealing and reduced locking within the thread pool queues.&#160; By using the default <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler</a>, our Tasks are run asynchronously on the <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx" target="_blank">ThreadPool</a>.</p>
<p>There is one notable exception to my above statements when using the default <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler</a>.&#160; If a <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> is created with the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskcreationoptions(v=VS.100).aspx" target="_blank">TaskCreationOptions</a> set to TaskCreationOptions.LongRunning, the default <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler</a> will generate a new thread for that <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a>, at least <a href="http://social.msdn.microsoft.com/Forums/en-US/parallelextensions/thread/8304b44f-0480-488c-93a4-ec419327183b/" target="_blank">in the current implementation</a>.&#160; This is useful for <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Tasks</a> which will persist for most of the lifetime of your application, since it prevents your <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> from starving the <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx" target="_blank">ThreadPool</a> of one of it’s work threads.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> provides one other implementation of the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler</a> class.&#160; In addition to providing a way to schedule tasks on the <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.aspx" target="_blank">ThreadPool</a>, the framework allows you to create a <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler</a> which works within a specified <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx" target="_blank">SynchronizationContext</a>.&#160; This scheduler can be retrieved within a thread that provides a valid <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx" target="_blank">SynchronizationContext</a> by calling the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.fromcurrentsynchronizationcontext(v=VS.100).aspx" target="_blank">TaskScheduler.FromCurrentSynchronizationContext()</a> method.</p>
<p>This implementation of <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler</a> is intended for use with user interface development.&#160; <a href="http://msdn.microsoft.com/en-us/library/ms950424.aspx" target="_blank">Windows Forms</a> and <a href="http://msdn.microsoft.com/en-us/library/ms754130.aspx" target="_blank">Windows Presentation Foundation</a> both require any access to user interface controls to occur on the same thread that created the control.&#160; For example, if you want to set the text within a Windows Forms TextBox, and you’re working on a background thread, that UI call must be marshaled back onto the UI thread.&#160; The most common way this is handled depends on the framework being used.&#160; In Windows Forms, <a href="http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx" target="_blank">Control.Invoke</a> or <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.begininvoke(v=VS.90).aspx" target="_blank">Control.BeginInvoke</a> is most often used.&#160; In WPF, the equivelent calls are <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.invoke.aspx" target="_blank">Dispatcher.Invoke</a> or <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.begininvoke(v=VS.90).aspx" target="_blank">Dispatcher.BeginInvoke</a>.</p>
<p>As an example, say we’re working on a background thread, and we want to update a TextBlock in our user interface with a status label.&#160; The code would typically look something like:</p>
<pre class="csharpcode"><span class="rem">// Within background thread work...</span>
<span class="kwrd">string</span> status = GetUpdatedStatus();

Dispatcher.BeginInvoke(DispatcherPriority.Normal,
    <span class="kwrd">new</span> Action( () =&gt; 
        {
            statusLabel.Text = status;
        }));

<span class="rem">// Continue on in background method</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 works fine, but forces your method to take a dependency on WPF or Windows Forms.&#160; There is an alternative option, however.&#160; Both Windows Forms and WPF, when initialized, setup a <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx" target="_blank">SynchronizationContext</a> in their thread, which is available on the UI thread via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.current(v=VS.90).aspx" target="_blank">SynchronizationContext.Current</a> property.&#160; This context is used by classes such as <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" target="_blank">BackgroundWorker</a> to marshal calls back onto the UI thread in a framework-agnostic manner.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> provides the same functionality via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.fromcurrentsynchronizationcontext(v=VS.100).aspx" target="_blank">TaskScheduler.FromCurrentSynchronizationContext()</a> method.&#160; When setting up our Tasks, as long as we’re working on the UI thread, we can construct a <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler</a> via:</p>
<pre class="csharpcode">TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();</pre>
<p>We then can use this scheduler on any thread to marshal data back onto the UI thread.&#160; For example, our code above can then be rewritten as:</p>
<pre class="csharpcode"><span class="kwrd">string</span> status = GetUpdatedStatus();

(<span class="kwrd">new</span> Task(() =&gt; 
    {
        statusLabel.Text = status;
    }))
.Start(uiScheduler);

<span class="rem">// Continue on in background method</span></pre>
<p>This is nice since it allows us to write code that isn’t tied to Windows Forms or WPF, but is still fully functional with those technologies.&#160; I’ll discuss even more uses for the <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx" target="_blank">SynchronizationContext</a> based <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler</a> when I demonstrate task continuations, but even without continuations, this is a very useful construct.</p>
<p>In addition to the two implementations provided by the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a>, it is possible to implement your own <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler</a>.&#160; The <a href="http://code.msdn.microsoft.com/ParExtSamples" target="_blank">ParallelExtensionsExtras project within the Samples for Parallel Programming</a> provides nine sample <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(VS.100).aspx" target="_blank">TaskScheduler</a> implementations.&#160; These include schedulers which restrict the maximum number of concurrent tasks, run tasks on a single threaded apartment thread, use a new thread per task, and more.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/q4KzxNmFSI8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/03/18/parallelism-in-net-part-15-making-tasks-run-the-taskscheduler/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/03/18/parallelism-in-net-part-15-making-tasks-run-the-taskscheduler/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 14, The Different Forms of Task</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/5CBpXWsLko0/</link>
		<comments>http://reedcopsey.com/2010/03/17/parallelism-in-net-part-14-the-different-forms-of-task/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 00:56:57 +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/17/parallelism-in-net-part-14-the-different-types-of-tasks/</guid>
		<description><![CDATA[Before discussing Task creation and actual usage in concurrent environments, I will briefly expand upon my introduction of the Task class and provide a short explanation of the distinct forms of Task.&#160; The Task Parallel Library includes four distinct, though related, variations on the Task class. In my introduction to the Task class, I focused [...]]]></description>
				<content:encoded><![CDATA[<p>Before discussing <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> creation and actual usage in concurrent environments, I will briefly expand upon <a href="http://reedcopsey.com/2010/03/15/parallelism-in-net-part-13-introducing-the-task-class/" target="_blank">my introduction of the Task class</a> and provide a short explanation of the distinct forms of Task.&#160; The <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> includes four distinct, though related, variations on the <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a>.</p>
<p> <span id="more-242"></span>In <a href="http://reedcopsey.com/2010/03/15/parallelism-in-net-part-13-introducing-the-task-class/" target="_blank">my introduction to the Task class</a>, I focused on the most basic version of <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a>.&#160; This version of Task, the standard <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a>, is most often used with an <a href="http://msdn.microsoft.com/en-us/library/system.action(v=VS.100).aspx" target="_blank">Action delegate</a>.&#160; This allows you to implement for each task within the <a href="http://reedcopsey.com/2010/03/05/parallelism-in-net-part-12-more-on-task-decomposition/" target="_blank">task decomposition</a> as a single delegate.
</p>
<p>Typically, when using the new threading constructs in .NET 4 and the <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a>, we use <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" target="_blank">lambda expressions</a> to define anonymous methods.&#160; The advantage of using a <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" target="_blank">lambda expression</a> is that it allows the <a href="http://msdn.microsoft.com/en-us/library/system.action(v=VS.100).aspx" target="_blank">Action delegate</a> to directly use variables in the calling scope.&#160; This eliminates the need to make separate Task classes for <a href="http://msdn.microsoft.com/en-us/library/018hxwa8(v=VS.100).aspx" target="_blank">Action&lt;T&gt;</a>, <a href="http://msdn.microsoft.com/en-us/library/bb549311(v=VS.100).aspx" target="_blank">Action&lt;T1,T2&gt;</a>, and all of the other Action&lt;…&gt; delegate types.&#160; As an example, suppose we wanted to make a Task to handle the <a href="http://reedcopsey.com/2010/03/05/parallelism-in-net-part-12-more-on-task-decomposition/" target="_blank"><em>”Show Splash”</em> task from our earlier decomposition</a>.&#160; Even if this task required parameters, such as a message to display, we could still use an <a href="http://msdn.microsoft.com/en-us/library/system.action(v=VS.100).aspx" target="_blank">Action delegate</a> specified via a lambda:</p>
<pre class="csharpcode"><span class="rem">// Store this as a local variable</span>
<span class="kwrd">string</span> messageForSplashScreen = GetSplashScreenMessage();
<span class="rem">// Create our task</span>
Task showSplashTask = <span class="kwrd">new</span> Task(
    () =&gt;
        {
            <span class="rem">// We can use variables in our outer scope, </span>
            <span class="rem">// as well as methods scoped to our class!</span>
            <span class="kwrd">this</span>.DisplaySplashScreen(messageForSplashScreen);
        });</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><!-- .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; } -->This provides a huge amount of flexibility.&#160; We can use this single form of task for any task which performs an operation, provided the only information we need to track is whether the task has completed successfully or not.&#160; This leads to my first observation:</p>
<p><strong>Use a Task with a System.Action delegate for any task for which no result is generated.</strong></p>
<p>This observation leads to an obvious corollary: we also need a way to define a task which generates a result.&#160; The <a href="http://msdn.microsoft.com/en-us/library/dd460717(VS.100).aspx" target="_blank">Task Parallel Library</a> provides this via the <a href="http://msdn.microsoft.com/en-us/library/dd321424(v=VS.100).aspx" target="_blank">Task&lt;TResult&gt; class</a>.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd321424(v=VS.100).aspx" target="_blank">Task&lt;TResult&gt;</a> subclasses the standard <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a>, providing one additional feature – the ability to return a value back to the user of the task.&#160; This is done by switching from providing an <a href="http://msdn.microsoft.com/en-us/library/system.action(v=VS.100).aspx" target="_blank">Action delegate</a> to providing a <a href="http://msdn.microsoft.com/en-us/library/bb534960(v=VS.100).aspx" target="_blank">Func&lt;TResult&gt; delegate</a>.&#160; If we decompose our problem, and we realize we have one task where its result is required by a future operation, this can be handled via <a href="http://msdn.microsoft.com/en-us/library/dd321424(v=VS.100).aspx" target="_blank">Task&lt;TResult&gt;</a>.&#160; For example, suppose we want to make a task for our <a href="http://reedcopsey.com/2010/03/05/parallelism-in-net-part-12-more-on-task-decomposition/" target="_blank">“<em>Check for Update</em>” task</a>, we could do:</p>
<pre class="csharpcode">Task&lt;<span class="kwrd">bool</span>&gt; checkForUpdateTask = <span class="kwrd">new</span> Task&lt;<span class="kwrd">bool</span>&gt;(
    () =&gt;
        {
            <span class="kwrd">return</span> <span class="kwrd">this</span>.CheckWebsiteForUpdate();
        });</pre>
<p>
  <br />Later, we would start this task, and perform some other work.&#160; At any point in the future, we could get the value from the <a href="http://msdn.microsoft.com/en-us/library/dd321468(v=VS.100).aspx" target="_blank">Task&lt;TResult&gt;.Result</a> property, which will cause our thread to block until the task has finished processing:</p>
<p></p>
<pre class="csharpcode"><span class="rem">// This uses Task&lt;bool&gt; checkForUpdateTask generated above...</span>
<span class="rem">// Start the task, typically on a background thread</span>
checkForUpdateTask.Start();

<span class="rem">// Do some other work on our current thread</span>
<span class="kwrd">this</span>.DoSomeWork();

<span class="rem">// Discover, from our background task, whether an update is available</span>
<span class="rem">// This will block until our task completes</span>
<span class="kwrd">bool</span> updateAvailable = checkForUpdateTask.Result;</pre>
<p>This leads me to my second observation:</p>
<p><strong>Use a Task&lt;TResult&gt; with a System.Func&lt;TResult&gt; delegate for any task which generates a result.</strong></p>
<p><a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> and <a href="http://msdn.microsoft.com/en-us/library/dd321424(v=VS.100).aspx" target="_blank">Task&lt;TResult&gt;</a> provide a much cleaner alternative to the previous <a href="http://msdn.microsoft.com/en-us/library/ms228969(v=VS.90).aspx" target="_blank">Asynchronous Programming design patterns</a> in the .NET framework.&#160; Instead of trying to implement <a href="http://msdn.microsoft.com/en-us/library/system.iasyncresult(v=VS.90).aspx" target="_blank">IAsyncResult</a>, and providing BeginXXX() and EndXXX() methods, implementing an asynchronous programming API can be as simple as creating a method that returns a Task or Task&lt;TResult&gt;.&#160; The client side of the pattern also is dramatically simplified – the client can call a method, then either choose to call <a href="http://msdn.microsoft.com/en-us/library/dd235635(v=VS.100).aspx" target="_blank">task.Wait()</a> or use <a href="http://msdn.microsoft.com/en-us/library/dd321468(v=VS.100).aspx" target="_blank">task.Result</a> when it needs to wait for the operation’s completion.</p>
<p>While this provides a much cleaner model for future APIs, there is quite a bit of infrastructure built around the current <a href="http://msdn.microsoft.com/en-us/library/ms228969(v=VS.90).aspx" target="_blank">Asynchronous Programming design patterns</a>.&#160; In order to provide a model to work with existing APIs, two other forms of Task exist.&#160; There is a constructor for <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> which takes an <a href="http://msdn.microsoft.com/en-us/library/018hxwa8(v=VS.100).aspx" target="_blank">Action&lt;Object&gt;</a> and a state parameter.&#160; In addition, there is a constructor for creating a <a href="http://msdn.microsoft.com/en-us/library/dd321424(v=VS.100).aspx" target="_blank">Task&lt;TResult&gt;</a> which takes a <a href="http://msdn.microsoft.com/en-us/library/bb549151(v=VS.100).aspx" target="_blank">Func&lt;Object, TResult&gt;</a> as well as a state parameter.&#160; When using these constructors, the state parameter is stored in the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.asyncstate(v=VS.100).aspx" target="_blank">Task.AsyncState property</a>.</p>
<p>While these two overloads exist, and are usable directly, I strongly recommend avoiding this for new development.&#160; The two forms of Task which take an object state parameter exist primarily for <a href="http://msdn.microsoft.com/en-us/library/dd997423(v=VS.100).aspx" target="_blank">interoperability with traditional .NET Asynchronous Programming methodologies</a>.&#160; Using <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" target="_blank">lambda expressions</a> to capture variables from the scope of the creator is a much cleaner approach than using the untyped state parameters, since <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" target="_blank">lambda expressions</a> provide full type safety without introducing new variables.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/5CBpXWsLko0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/03/17/parallelism-in-net-part-14-the-different-forms-of-task/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/03/17/parallelism-in-net-part-14-the-different-forms-of-task/</feedburner:origLink></item>
		<item>
		<title>Parallelism in .NET – Part 13, Introducing the Task class</title>
		<link>http://feedproxy.google.com/~r/ReedCopsey/~3/gfuFS-CUKE8/</link>
		<comments>http://reedcopsey.com/2010/03/15/parallelism-in-net-part-13-introducing-the-task-class/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 20:47:30 +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/15/parallelism-in-net-part-13-introducing-the-task-class/</guid>
		<description><![CDATA[Once we’ve used a task-based decomposition to decompose a problem, we need a clean abstraction usable to implement the resulting decomposition.&#160; Given that task decomposition is founded upon defining discrete tasks, .NET 4 has introduced a new API for dealing with task related issues, the aptly named Task class. The Task class is a wrapper [...]]]></description>
				<content:encoded><![CDATA[<p>Once we’ve used a <a href="http://reedcopsey.com/2010/03/05/parallelism-in-net-part-12-more-on-task-decomposition/" target="_blank">task-based decomposition</a> to decompose a problem, we need a clean abstraction usable to implement the resulting decomposition.&#160; Given that <a href="http://reedcopsey.com/2010/03/05/parallelism-in-net-part-12-more-on-task-decomposition/" target="_blank">task decomposition is founded upon defining discrete tasks</a>, .NET 4 has introduced a new API for dealing with task related issues, the aptly named <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a>.</p>
<p> <span id="more-217"></span>
<p>The <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a> is a wrapper for a delegate representing a single, discrete task within your decomposition.&#160; We will go into various methods of construction for tasks later, but, when reduced to its fundamentals, an instance of a <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> is nothing more than a wrapper around a delegate with some utility functionality added.&#160; </p>
<p>In order to fully understand the Task class within the new <a href="http://msdn.microsoft.com/en-us/library/dd460717(v=VS.100).aspx" target="_blank">Task Parallel Library</a>, it is important to realize that a task really is just a delegate – nothing more.&#160; In particular, note that I never mentioned threading or parallelism in my description of a <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a>.&#160; Although the <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class </a>exists in the new <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks(v=VS.100).aspx" target="_blank">System.Threading.Tasks</a> namespace:</p>
<p><strong>Tasks are not directly related to threads or multithreading.</strong></p>
<p>Of course, <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task</a> instances will typically be used in our implementation of concurrency within an application, but the <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a> itself does not provide the concurrency used.&#160; The Task API supports using Tasks in an entirely single threaded, synchronous manner.</p>
<p>Tasks are very much like standard delegates.&#160; You can execute a task synchronously via <a href="http://msdn.microsoft.com/en-us/library/dd321435(v=VS.100).aspx" target="_blank">Task.RunSynchronously()</a>, or you can use <a href="http://msdn.microsoft.com/en-us/library/dd270682(v=VS.100).aspx" target="_blank">Task.Start()</a> to schedule a task to run, typically asynchronously.&#160; This is very similar to using delegate.Invoke to execute a delegate synchronously, or using delegate.BeginInvoke to execute it asynchronously.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a> adds some nice functionality on top of a standard delegate which improves usability in both synchronous and multithreaded environments.</p>
<p>The first addition provided by Task is a means of handling cancellation via the new <a href="http://msdn.microsoft.com/en-us/library/dd997364(VS.100).aspx" target="_blank">unified cancellation mechanism of .NET 4</a>.&#160; If the wrapped delegate within a Task raises an <a href="http://msdn.microsoft.com/en-us/library/system.operationcanceledexception(v=VS.100).aspx" target="_blank">OperationCanceledException</a> during it’s operation, which is typically generated via calling <a href="http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken.throwifcancellationrequested(v=VS.100).aspx" target="_blank">ThrowIfCancellationRequested</a> on a <a href="http://msdn.microsoft.com/en-us/library/dd384802(v=VS.100).aspx" target="_blank">CancellationToken</a>, or if the <a href="http://msdn.microsoft.com/en-us/library/dd384802(v=VS.100).aspx" target="_blank">CancellationToken</a> used to construct a Task instance is flagged as canceled, the Task’s <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.iscanceled(v=VS.100).aspx" target="_blank">IsCanceled property</a> will be set to true automatically.&#160; This provides a clean way to determine whether a Task has been canceled, often without requiring specific exception handling.</p>
<p>Tasks also provide a clean API which can be used for waiting on a task.&#160; Although the <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class explicitly implements IAsyncResult</a>, Tasks provide a nicer usage model than the <a href="http://msdn.microsoft.com/en-us/library/ms228963.aspx" target="_blank">traditional .NET Asynchronous Programming Model</a>.&#160; Instead of needing to track an IAsyncResult handle, you can just directly call <a href="http://msdn.microsoft.com/en-us/library/dd235635(v=VS.100).aspx" target="_blank">Task.Wait()</a> to block until a Task has completed.&#160; Overloads exist for providing a timeout, a CancellationToken, or both to prevent waiting indefinitely.&#160; In addition, the <a href="http://msdn.microsoft.com/en-us/library/dd235678(v=VS.100).aspx" target="_blank">Task class</a> provides static methods for waiting on multiple tasks – <a href="http://msdn.microsoft.com/en-us/library/dd270695(v=VS.100).aspx" target="_blank">Task.WaitAll</a> and <a href="http://msdn.microsoft.com/en-us/library/dd270672(v=VS.100).aspx" target="_blank">Task.WaitAny</a>, again with overloads providing time out options.&#160; This provides a very simple, clean API for waiting on single or multiple tasks.</p>
<p>Finally, Tasks provide a much nicer model for Exception handling.&#160; If the delegate wrapped within a Task raises an exception, the exception will automatically get wrapped into an <a href="http://msdn.microsoft.com/en-us/library/system.aggregateexception(v=VS.100).aspx" target="_blank">AggregateException</a> and exposed via the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.exception(v=VS.100).aspx" target="_blank">Task.Exception property</a>.&#160; This exception is stored with the Task directly, and does not tear down the application.&#160; Later, when <a href="http://msdn.microsoft.com/en-us/library/dd235635(v=VS.100).aspx" target="_blank">Task.Wait()</a> (or <a href="http://msdn.microsoft.com/en-us/library/dd270695(v=VS.100).aspx" target="_blank">Task.WaitAll</a> or <a href="http://msdn.microsoft.com/en-us/library/dd270672(v=VS.100).aspx" target="_blank">Task.WaitAny</a>) is called on this task, an AggregateException will be raised at that point if any of the tasks raised an exception.&#160; </p>
<p>For example, suppose we have the following code:</p>
<pre class="csharpcode">Task taskOne = <span class="kwrd">new</span> Task(
                       () =&gt;
                       {
                           <span class="kwrd">throw</span> <span class="kwrd">new</span> ApplicationException(<span class="str">&quot;Random Exception!&quot;</span>);
                       });
Task taskTwo = <span class="kwrd">new</span> Task(
                       () =&gt;
                       {
                           <span class="kwrd">throw</span> <span class="kwrd">new</span> ArgumentException(<span class="str">&quot;Different exception here&quot;</span>);
                       });

<span class="rem">// Start the tasks</span>
taskOne.Start();
taskTwo.Start();

<span class="kwrd">try</span>
{
    Task.WaitAll(<span class="kwrd">new</span>[] { taskOne, taskTwo });
}
<span class="kwrd">catch</span> (AggregateException e)
{
    Console.WriteLine(e.InnerExceptions.Count);
    <span class="kwrd">foreach</span> (var inner <span class="kwrd">in</span> e.InnerExceptions)
        Console.WriteLine(inner.Message);
}</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, our routine will print:</p>
<pre>2
Different exception here
Random Exception!</pre>
<p>Note that we had two separate tasks, each of which raised two distinctly different types of exceptions.&#160; We can handle this cleanly, with very little code, in a much nicer manner than the <a href="http://msdn.microsoft.com/en-us/library/ms228969(v=VS.90).aspx" target="_blank">Asynchronous Programming API</a>.&#160; We no longer need to handle <a href="http://msdn.microsoft.com/en-us/library/system.reflection.targetinvocationexception.aspx" target="_blank">TargetInvocationException</a> or worry about implementing the <a href="http://msdn.microsoft.com/en-us/library/wewwczdw(v=VS.90).aspx" target="_blank">Event-based Asynchronous Pattern</a> properly by setting the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asynccompletedeventargs.error(v=VS.90).aspx" target="_blank">AsyncCompletedEventArgs.Error</a> property.&#160; Instead, we just raise our exception as normal, and handle <a href="http://msdn.microsoft.com/en-us/library/system.aggregateexception(v=VS.100).aspx" target="_blank">AggregateException</a> in a single location in our calling code.</p>
<img src="http://feeds.feedburner.com/~r/ReedCopsey/~4/gfuFS-CUKE8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://reedcopsey.com/2010/03/15/parallelism-in-net-part-13-introducing-the-task-class/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://reedcopsey.com/2010/03/15/parallelism-in-net-part-13-introducing-the-task-class/</feedburner:origLink></item>
		<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 [...]]]></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>3</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>8</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>
	</channel>
</rss>
