<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Udi Dahan - The Software Simplist &#187; Threading</title>
	<atom:link href="http://www.udidahan.com/category/threading/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.udidahan.com</link>
	<description>Enterprise Development Expert &#38; SOA Specialist</description>
	<lastBuildDate>Sat, 24 Jul 2010 20:06:18 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Domain Events &#8211; Take 2</title>
		<link>http://www.udidahan.com/2008/08/25/domain-events-take-2/</link>
		<comments>http://www.udidahan.com/2008/08/25/domain-events-take-2/#comments</comments>
		<pubDate>Mon, 25 Aug 2008 13:40:41 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://www.udidahan.com/2008/08/25/domain-events-take-2/</guid>
		<description><![CDATA[Update: The next post in this series is now online here.
My previous post on how to create fully encapsulated domain models introduced the concept of events as a core pattern of communication from the domain back to the service layer. In that post, I put up enough code to get the idea across but didn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<p><b>Update:</b> The next post in this series is now online <a href="http://www.udidahan.com/2009/06/14/domain-events-salvation/">here</a>.</p>
<p>My previous post on <a href="http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models/">how to create fully encapsulated domain models</a> introduced the concept of events as a core pattern of communication from the domain back to the service layer. In that post, I put up enough code to get the idea across but didn&#8217;t address issues like memory leaks and multi-threading. This post will show the solution to those two critical points.</p>
<p> <center><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="63" alt="" src="http://www.udidahan.com/wp-content/uploads/image43.png" width="500" border="0"></center>
</p>
<p>I&#8217;ve snipped out one of the events in the previous example for brevity.</p>
<h3>Previous API</h3>
<p>The previous API looked like this:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ -->
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> DomainEvents</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">event</span> EventHandler GameReportedLost;</pre>
<pre><span class="lnum">   4:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RaiseGameReportedLostEvent()</pre>
<pre class="alt"><span class="lnum">   5:  </span>     {</pre>
<pre><span class="lnum">   6:  </span>           <span class="kwrd">if</span> (GameReportedLost != <span class="kwrd">null</span>)</pre>
<pre class="alt"><span class="lnum">   7:  </span>               GameReportedLost(<span class="kwrd">null</span>, <span class="kwrd">null</span>);</pre>
<pre><span class="lnum">   8:  </span>     }</pre>
<pre class="alt"><span class="lnum">   9:  </span>&nbsp;</pre>
<pre><span class="lnum">  10:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">event</span> EventHandler CartIsFull;</pre>
<pre class="alt"><span class="lnum">  11:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">void</span> RaiseCartIsFull()</pre>
<pre><span class="lnum">  12:  </span>     {</pre>
<pre class="alt"><span class="lnum">  13:  </span>           <span class="kwrd">if</span> (CartIsFull != <span class="kwrd">null</span>)</pre>
<pre><span class="lnum">  14:  </span>               CartIsFull(<span class="kwrd">null</span>, <span class="kwrd">null</span>);</pre>
<pre class="alt"><span class="lnum">  15:  </span>     }</pre>
<pre><span class="lnum">  16:  </span>}</pre>
</div>
<p>One thing that we want to keep in the solution is that all the code to define events, their names, and the parameters they bring will be in one place &#8211; in this case, the DomainEvents class. One thing that we&#8217;d like to fix is the amount of code needed to define an event.</p>
<h3>Previous Service Layer</h3>
<p>Here&#8217;s what our previous service layer code looked like:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> AddGameToCartMessageHandler :</pre>
<pre><span class="lnum">   2:  </span>    BaseMessageHandler&lt;AddGameToCartMessage&gt;</pre>
<pre class="alt"><span class="lnum">   3:  </span>{</pre>
<pre><span class="lnum">   4:  </span>    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Handle(AddGameToCartMessage m)</pre>
<pre class="alt"><span class="lnum">   5:  </span>    {</pre>
<pre><span class="lnum">   6:  </span>        <span class="kwrd">using</span> (ISession session = SessionFactory.OpenSession())</pre>
<pre class="alt"><span class="lnum">   7:  </span>        <span class="kwrd">using</span> (ITransaction tx = session.BeginTransaction())</pre>
<pre><span class="lnum">   8:  </span>        {</pre>
<pre class="alt"><span class="lnum">   9:  </span>            ICart cart = session.Get&lt;ICart&gt;(m.CartId);</pre>
<pre><span class="lnum">  10:  </span>            IGame g = session.Get&lt;IGame&gt;(m.GameId);</pre>
<pre class="alt"><span class="lnum">  11:  </span>&nbsp;</pre>
<pre><span class="lnum">  12:  </span>            Domain.DomainEvents.GameReportedLost +=</pre>
<pre class="alt"><span class="lnum">  13:  </span>              gameReportedLost;</pre>
<pre><span class="lnum">  14:  </span>            Domain.DomainEvents.CartIsFull +=</pre>
<pre class="alt"><span class="lnum">  15:  </span>              cartIsFull;</pre>
<pre class="alt"><span class="lnum">  16:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  17:  </span>            cart.Add(g);</pre>
<pre><span class="lnum">  18:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  19:  </span>            Domain.DomainEvents.GameReportedLost -=</pre>
<pre><span class="lnum">  20:  </span>              gameReportedLost;</pre>
<pre class="alt"><span class="lnum">  21:  </span>            Domain.DomainEvents.CartIsFull -=</pre>
<pre><span class="lnum">  22:  </span>              cartIsFull;</pre>
<pre class="alt"><span class="lnum">  23:  </span>&nbsp;</pre>
<pre><span class="lnum">  24:  </span>            tx.Commit();</pre>
<pre class="alt"><span class="lnum">  25:  </span>        }</pre>
<pre><span class="lnum">  26:  </span>    }</pre>
<pre class="alt"><span class="lnum">  27:  </span>&nbsp;</pre>
<pre><span class="lnum">  28:  </span>    <span class="kwrd">private</span> EventHandler gameReportedLost = <span class="kwrd">delegate</span> { </pre>
<pre class="alt"><span class="lnum">  29:  </span>          Bus.Return((<span class="kwrd">int</span>)ErrorCodes.GameReportedLost);</pre>
<pre><span class="lnum">  30:  </span>        };</pre>
<pre class="alt"><span class="lnum">  31:  </span>&nbsp;</pre>
<pre><span class="lnum">  32:  </span>    <span class="kwrd">private</span> EventHandler cartIsFull = <span class="kwrd">delegate</span> { </pre>
<pre class="alt"><span class="lnum">  33:  </span>          Bus.Return((<span class="kwrd">int</span>)ErrorCodes.CartIsFull);</pre>
<pre><span class="lnum">  34:  </span>        };</pre>
<pre class="alt"><span class="lnum">  35:  </span>    }</pre>
<pre><span class="lnum">  36:  </span>}</pre>
</div>
<p>Another thing that should be improved is the amount of code needed in the service layer.</p>
<p>Raising an event, though, should still be fairly simple &#8211; one line of code similar to DomainEvents.RaiseGameReportedLost().</p>
<h3>New API</h3>
<p>Here&#8217;s what the new API looks like:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> DomainEvents</pre>
<pre><span class="lnum">   2:  </span>{</pre>
<pre class="alt"><span class="lnum">   3:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> DomainEvent&lt;IGame&gt; GameReportedLost = </pre>
<pre><span class="lnum">   4:  </span>                                          <span class="kwrd">new</span> DomainEvent&lt;IGame&gt;;</pre>
<pre class="alt"><span class="lnum">   5:  </span>&nbsp;</pre>
<pre><span class="lnum">   6:  </span>     <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> DomainEvent&lt;ICart&gt; CartIsFull=</pre>
<pre class="alt"><span class="lnum">   7:  </span>                                          <span class="kwrd">new</span> DomainEvent&lt;ICart&gt;;</pre>
<pre><span class="lnum">   8:  </span>}</pre>
</div>
<p>It looks like we&#8217;ve managed to bring down the complexity of defining an event.</p>
<p>Raising an event is slightly different, but still only one line of code (&#8221;this&#8221; refers to the Cart class that is calling this API): DomainEvents.CartIsFull.Raise(<span class="kwrd">this</span>);</p>
<h3>New Service Layer</h3>
<p>The advantage of having a disposable domain event allows us to use the &#8220;using&#8221; construct for cleanup.</p>
<p><p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> AddGameToCartMessageHandler :</pre>
<pre><span class="lnum">   2:  </span>    BaseMessageHandler&lt;AddGameToCartMessage&gt;</pre>
<pre class="alt"><span class="lnum">   3:  </span>{</pre>
<pre><span class="lnum">   4:  </span>    <span class="kwrd">public</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Handle(AddGameToCartMessage m)</pre>
<pre class="alt"><span class="lnum">   5:  </span>    {</pre>
<pre><span class="lnum">   6:  </span>        <span class="kwrd">using</span> (ISession session = SessionFactory.OpenSession())</pre>
<pre class="alt"><span class="lnum">   7:  </span>        <span class="kwrd">using</span> (ITransaction tx = session.BeginTransaction())</pre>
<pre><span class="lnum">   8:  </span>        <span class="kwrd">using</span> (DomainEvents.GameReportedLost.Register(gameReportedLost))</pre>
<pre class="alt"><span class="lnum">   9:  </span>        <span class="kwrd">using</span> (DomainEvents.CartIsFull.Register(cartIsFull))</pre>
<pre><span class="lnum">  10:   </span>       {</pre>
<pre class="alt"><span class="lnum">  11:  </span>            ICart cart = session.Get&lt;ICart&gt;(m.CartId);</pre>
<pre><span class="lnum">  12:  </span>            IGame g = session.Get&lt;IGame&gt;(m.GameId);</pre>
<pre class="alt"><span class="lnum">  13:  </span>&nbsp;</pre>
<pre><span class="lnum">  14:  </span>            cart.Add(g);</pre>
<pre class="alt"><span class="lnum">  15:  </span>&nbsp;</pre>
<pre><span class="lnum">  16:  </span>            tx.Commit();</pre>
<pre class="alt"><span class="lnum">  17:  </span>        }</pre>
<pre><span class="lnum">  18:  </span>    }</pre>
<pre class="alt"><span class="lnum">  19:  </span>&nbsp;</pre>
<pre><span class="lnum">  20:  </span>    <span class="kwrd">private</span> Action&lt;IGame&gt; gameReportedLost = <span class="kwrd">delegate</span> { </pre>
<pre class="alt"><span class="lnum">  21:  </span>          Bus.Return((<span class="kwrd">int</span>)ErrorCodes.GameReportedLost);</pre>
<pre><span class="lnum">  22:  </span>        };</pre>
<pre class="alt"><span class="lnum">  23:  </span>&nbsp;</pre>
<pre><span class="lnum">  24:  </span>    <span class="kwrd">private</span> Action&lt;ICart&gt; cartIsFull = <span class="kwrd">delegate</span> { </pre>
<pre class="alt"><span class="lnum">  25:  </span>          Bus.Return((<span class="kwrd">int</span>)ErrorCodes.CartIsFull);</pre>
<pre><span class="lnum">  26:  </span>        };</pre>
<pre class="alt"><span class="lnum">  27:  </span>    }</pre>
<pre><span class="lnum">  28:  </span>}</pre>
</div>
<p>I also want to mention that you don&#8217;t necessarily have to have the same service layer object handle these events as that which calls the domain objects. In other words, we can have singleton objects handling these events for things like sending emails, notifying external systems, and auditing.</p>
<h3>The Infrastructure</h3>
<p>The infrastructure that makes all this possible (in a thread-safe way) is quite simple and made up of two parts, the DomainEvent that we saw being used above, and the DomainEventRegistrationRemover which handles the disposing:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">using</span> System;</pre>
<pre><span class="lnum">   2:  </span><span class="kwrd">using</span> System.Collections.Generic;</pre>
<pre class="alt"><span class="lnum">   3:  </span>&nbsp;</pre>
<pre><span class="lnum">   4:  </span><span class="kwrd">namespace</span> DomainEventInfrastructure</pre>
<pre class="alt"><span class="lnum">   5:  </span>{</pre>
<pre><span class="lnum">   6:  </span>    <span class="kwrd">public</span> <span class="kwrd">class</span> DomainEvent&lt;E&gt; </pre>
<pre class="alt"><span class="lnum">   7:  </span>    {</pre>
<pre><span class="lnum">   8:  </span>        [ThreadStatic] </pre>
<pre class="alt"><span class="lnum">   9:  </span>        <span class="kwrd">private</span> <span class="kwrd">static</span> List&lt;Action&lt;E&gt;&gt; _actions; </pre>
<pre><span class="lnum">  10:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  11:  </span>        <span class="kwrd">protected</span> List&lt;Action&lt;E&gt;&gt; actions </pre>
<pre><span class="lnum">  12:  </span>        {</pre>
<pre class="alt"><span class="lnum">  13:  </span>            get { </pre>
<pre><span class="lnum">  14:  </span>                <span class="kwrd">if</span> (_actions == <span class="kwrd">null</span>) </pre>
<pre class="alt"><span class="lnum">  15:  </span>                    _actions = <span class="kwrd">new</span> List&lt;Action&lt;E&gt;&gt;(); </pre>
<pre><span class="lnum">  16:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  17:  </span>                <span class="kwrd">return</span> _actions; </pre>
<pre><span class="lnum">  18:  </span>            }</pre>
<pre class="alt"><span class="lnum">  19:  </span>        }</pre>
<pre><span class="lnum">  20:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  21:  </span>        <span class="kwrd">public</span> IDisposable Register(Action&lt;E&gt; callback) </pre>
<pre><span class="lnum">  22:  </span>        {</pre>
<pre class="alt"><span class="lnum">  23:  </span>            actions.Add(callback);</pre>
<pre><span class="lnum">  24:  </span>            <span class="kwrd">return</span> <span class="kwrd">new</span> DomainEventRegistrationRemover(<span class="kwrd">delegate</span></pre>
<pre class="alt"><span class="lnum">  25:  </span>                {</pre>
<pre><span class="lnum">  26:  </span>                    actions.Remove(callback);</pre>
<pre class="alt"><span class="lnum">  27:  </span>                }</pre>
<pre><span class="lnum">  28:  </span>            ); </pre>
<pre class="alt"><span class="lnum">  29:  </span>        }</pre>
<pre><span class="lnum">  30:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">  31:  </span>        <span class="kwrd">public</span> <span class="kwrd">void</span> Raise(E args) </pre>
<pre><span class="lnum">  32:  </span>        {</pre>
<pre class="alt"><span class="lnum">  33:  </span>            <span class="kwrd">foreach</span> (Action&lt;E&gt; action <span class="kwrd">in</span> actions) </pre>
<pre><span class="lnum">  34:  </span>                action.Invoke(args);</pre>
<pre class="alt"><span class="lnum">  35:  </span>        }</pre>
<pre><span class="lnum">  36:  </span>    }</pre>
<pre class="alt"><span class="lnum">  37:  </span>}</pre>
<pre><span class="lnum">  38:  </span>&nbsp;</pre>
</div>
<p>Note that the invocation list of the domain event is thread static, meaning that each thread gets its own copy &#8211; even though they&#8217;re all working with the same instance of the domain event.</p>
<p>Here&#8217;s the DomainEventRegistrationRemover &#8211; even simpler:</p>
<p><!-- code formatted by http://manoli.net/csharpformat/ --></p>
<div class="csharpcode">
<pre class="alt"><span class="lnum">   1:  </span><span class="kwrd">using</span> System;</pre>
<pre><span class="lnum">   2:  </span>&nbsp;</pre>
<pre class="alt"><span class="lnum">   3:  </span><span class="kwrd">namespace</span> DomainEventInfrastructure</pre>
<pre><span class="lnum">   4:  </span>{</pre>
<pre class="alt"><span class="lnum">   5:  </span>    <span class="kwrd">public</span> <span class="kwrd">class</span> DomainEventRegistrationRemover : IDisposable </pre>
<pre><span class="lnum">   6:  </span>    {</pre>
<pre class="alt"><span class="lnum">   7:  </span>        <span class="kwrd">private</span> <span class="kwrd">readonly</span> Action CallOnDispose;</pre>
<pre><span class="lnum">   8:  </span> </pre>
<pre class="alt"><span class="lnum">   9:  </span>        <span class="kwrd">public</span> DomainEventRegistrationRemover(Action ToCall) </pre>
<pre><span class="lnum">  10:  </span>        {</pre>
<pre class="alt"><span class="lnum">  11:  </span>            <span class="kwrd">this</span>.CallOnDispose = ToCall; </pre>
<pre><span class="lnum">  12:  </span>        }</pre>
<pre class="alt"><span class="lnum">  13:  </span>&nbsp;</pre>
<pre><span class="lnum">  14:  </span>        <span class="kwrd">public</span> <span class="kwrd">void</span> Dispose() </pre>
<pre class="alt"><span class="lnum">  15:  </span>        {</pre>
<pre><span class="lnum">  16:  </span>            <span class="kwrd">this</span>.CallOnDispose.DynamicInvoke();</pre>
<pre class="alt"><span class="lnum">  17:  </span>        }</pre>
<pre><span class="lnum">  18:  </span>    }</pre>
<pre class="alt"><span class="lnum">  19:  </span>}</pre>
</div>
<p>For your convenience, I&#8217;ve made these available for <a href="http://www.udidahan.com/wp-content/uploads/domaineventinfrastructure.zip">download here</a>.</p>
<p>I also want to add that if you haven&#8217;t looked at the comments on the original post &#8211; there&#8217;s some really good stuff there (36 comments so far). <a href="http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models">Take a look</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2008/08/25/domain-events-take-2/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Prism &#8211; Occasionally Connected?</title>
		<link>http://www.udidahan.com/2008/06/09/prism-occasionally-connected/</link>
		<comments>http://www.udidahan.com/2008/06/09/prism-occasionally-connected/#comments</comments>
		<pubDate>Mon, 09 Jun 2008 12:46:56 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Smart Client]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2008/06/09/prism-occasionally-connected/</guid>
		<description><![CDATA[Prism, AKA Composite Application Guidance + Composite Application Library, is rolling towards a release. I&#8217;ve been talking with Glenn Block quite a bit about Prism, and am even on the advisory board (what were they thinking?).
One of the topics not covered by Prism is occasional connectivity, and I would like to say a word or [...]]]></description>
			<content:encoded><![CDATA[<p>Prism, AKA Composite Application Guidance + Composite Application Library, is rolling towards a release. I&#8217;ve been talking with Glenn Block quite a bit about Prism, and am even on the advisory board (what were they thinking?).</p>
<p>One of the topics <em>not</em> covered by Prism is occasional connectivity, and I would like to say a word or two about that. First of all, if you&#8217;re building a standalone client (one that doesn&#8217;t communicate with anything), then there&#8217;s a good chance that Prism isn&#8217;t for you, although you could be composing other standalone client modules. So, if your client isn&#8217;t communicating with anything, well, then this post probably won&#8217;t interest you that much. Let&#8217;s start with&#8230;</p>
<h3>Physics<img style="border-right: 0px; border-top: 0px; margin: 0px 0px 10px 10px; border-left: 0px; border-bottom: 0px" height="192" alt="Physics" src="http://udidahan.weblogs.us/wp-content/uploads/image22.png" width="244" align="right" border="0"> </h3>
<p>Networks fail. Period. </p>
<p>This means that your client machine will not always be connected to other servers. </p>
<p>Also, servers fail &#8211; critical Windows patches and just regular power outages.</p>
<blockquote><p>Ergo, your &#8220;smart&#8221; client will be occasionally connected, whether you planned for it or not.</p>
</blockquote>
<p>And please don&#8217;t take this post as a &#8220;dumping on Prism&#8221; post &#8211; it isn&#8217;t intended that way. Rather, it is about how you should think about designing modules in Prism, and why.</p>
<h3>Modules and Connectivity</h3>
<p>Consider the case where we have two modules being composed in a single client. Each module communicates with a different server. Let&#8217;s call these modules Ma and Mb, and the servers Sa and Sb respectively. Now, let&#8217;s discuss what occurs given that the modules weren&#8217;t designed with occasional connectivity in mind.</p>
<blockquote><p>User clicks something in Mb which requires communication.</p>
<p>Mb tries to call Sb, say, over HTTP, using a regular web service invocation.</p>
<p>The calling thread, in this case, the one used for user interaction, is blocked waiting for a response from Sb.<a href="http://udidahan.weblogs.us/wp-content/uploads/image23.png"><img style="border-right: 0px; border-top: 0px; margin: 10px 0px 10px 10px; border-left: 0px; border-bottom: 0px" height="184" alt="image" src="http://udidahan.weblogs.us/wp-content/uploads/image-thumb19.png" width="244" align="right" border="0"></a></p>
<p>Sometime in this call, Sb fails, connectivity goes down, whatever. </p>
<p>30 seconds after the call, the HTTP connection times out.</p>
</blockquote>
<p>If something important were happening in Ma at the same time, the user couldn&#8217;t even <em>see</em> it, let alone do anything about it since the user interaction thread is stuck. This is a serious concern for the financial services domain, but in many others as well.</p>
<h3>You mean there&#8217;s more?</h3>
<p>I can go on, but I think that that&#8217;s enough to paint the picture that if you are building a smart client, there are a lot more things to think about than just learning Prism. That&#8217;s my main concern after witnessing what happened around the CAB. Given the learning curve around these frameworks many developers don&#8217;t seek to deepen their understanding beyond just becoming proficient with them. This isn&#8217;t just centered on the developers, evangelists in Microsoft tend to paint the picture this way:</p>
<blockquote><p>Once you understand X (CAB, Prism, BizTalk, whatever), all your problems are solved.</p>
</blockquote>
<p>That&#8217;s not to say there aren&#8217;t good things in those technologies, but that&#8217;s just it, they&#8217;re just <em>tools</em>. Silver hammers and &#8220;laser&#8221; guided saws do not a master carpenter make. There&#8217;s actually a pretty good chance the regular guy will saw their arm off.</p>
<h3>Help<a href="http://udidahan.weblogs.us/wp-content/uploads/image24.png"><img style="border-right: 0px; border-top: 0px; margin: 10px 0px 10px 10px; border-left: 0px; border-bottom: 0px" height="191" alt="image" src="http://udidahan.weblogs.us/wp-content/uploads/image-thumb20.png" width="244" align="right" border="0"></a></h3>
<p>I do hope more &#8220;instruction manuals&#8221; will be coming out of Microsoft on these topics. That&#8217;s not to say there aren&#8217;t any. Specifically on the topic of occasional connectivity, there is <a href="http://msdn.microsoft.com/en-us/library/ms998482.aspx">Chapter 4 of the Smart Client Architecture &amp; Design Guide</a>. Unfortunately, it doesn&#8217;t say anything about how that connects with the MVC/MVP being used client side (the bits affected by Prism). <a href="http://msdn.microsoft.com/en-us/library/ms998490.aspx">Chapter 6</a> of the same guide deals with the client-side threading, but doesn&#8217;t address issues like: </p>
<ul>
<li>Which model object instance are views bound to.</li>
<li>Do other threads have access to that object at the same time.</li>
<li>Which controller/presenter is responsible for giving that object to the view.</li>
<li>Do they need to clone it.</li>
<li>How deep should the clone be.</li>
<li>How do various controllers/presenters (which may be showing the same object in different views at the same time) communicate changes to their various independent clones.</li>
</ul>
<p>I haven&#8217;t yet documented all the patterns that answer these questions, but until I do (or Microsoft does), let me offer these few resources which I&#8217;ve put out over the years:</p>
<ul>
<li><a href="http://www.developer.com/design/article.php/3708006">Occasionally Connected Systems Architecture: The Client</a></li>
<li><a href="http://www.developer.com/design/article.php/3705396">Occasionally Connected Systems Architecture: Concurrency</a></li>
<li><a href="http://www.developer.com/design/article.php/3708006">Threading issues when smart clients reconnect</a></li>
<li>[Podcast] <a href="http://udidahan.weblogs.us/2007/04/17/podcast-occasionally-connected-smart-clients-and-adonet-sync-services/">Occasionally Connected Smart Clients and ADO.NET Sync Services</a></li>
</ul>
<p>There&#8217;s also some more links under the <a href="http://udidahan.weblogs.us/first-time-here/#smart_client">Smart Client link</a> of my <a href="http://udidahan.weblogs.us/first-time-here/">&#8220;First time here?&#8221; page</a>.</p>
<p>Also, please join me in asking Microsoft for an update to these guides &#8211; comments below or your own blog posts would be great.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2008/06/09/prism-occasionally-connected/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WCF, Smart Clients, and Deadlocks</title>
		<link>http://www.udidahan.com/2008/04/11/wcf-smart-clients-and-deadlocks/</link>
		<comments>http://www.udidahan.com/2008/04/11/wcf-smart-clients-and-deadlocks/#comments</comments>
		<pubDate>Fri, 11 Apr 2008 09:15:38 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[NServiceBus]]></category>
		<category><![CDATA[Simplicity]]></category>
		<category><![CDATA[Smart Client]]></category>
		<category><![CDATA[Threading]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2008/04/11/wcf-smart-clients-and-deadlocks/</guid>
		<description><![CDATA[There&#8217;s a new article up on MSDN describing how to write Smart Clients using WCF. The author is none other than WCF-Master Lowy and he goes over the multitude of ways you can deadlock yourself.
Here&#8217;s a taste:
UI Thread and Concurrency Management
Whenever you use hosting on the UI thread, deadlocks are possible. For example, the following [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s a new article up on MSDN describing how to write Smart Clients using WCF. The author is none other than <a href="http://www.idesign.net/">WCF-Master Lowy</a> and he goes over the multitude of ways you can deadlock yourself.</p>
<p>Here&#8217;s a taste:</p>
<blockquote><h3>UI Thread and Concurrency Management</h3>
<p>Whenever you use hosting on the UI thread, deadlocks are possible. For example, the following setup is guaranteed to result with a deadlock: A Windows Forms application is hosting a service with <b>UseSynchronizationContext</b> set to <b>true</b>, and UI thread affinity is established. The Windows Forms application then calls the service over one of its endpoints. The call to the service blocks the UI thread, while WCF posts a message to the UI thread to invoke the service. That message is never processed, because of the blocking UI thread—hence, the deadlock.
<p>Another possible case for a deadlock occurs when a Windows Forms application is hosting a service with <b>UseSynchronizationContext</b> set to <b>true</b> and UI thread affinity is established. The service receives a call from a remote client. That call is marshaled to the UI thread and is eventually executed on that thread. If the service is allowed to call out to another service, that can result in a deadlock if the callout causality tries somehow to update the UI or call back to the service’s endpoint, because all of the service instances that are associated with any endpoint (regardless of the service-instancing mode) share the same UI thread.
<p>Similarly, you risk a deadlock if the service is configured for reentrancy and it calls back to its client. You risk a deadlock if the callback causality tries to update the UI or enter the service, because that reentrance must be marshaled to the blocked UI thread.</p>
</blockquote>
<p>Actually, I have difficulty believing that Juval would go so far as to suggest that even the forms should be services, but he does:<br />
<blockquote>
<h3>Form as a Service</h3>
<p>The main motivation for hosting a WCF service on the UI thread is if the service must update the UI or the form. The problem is always: How does the service reach out and obtain a reference to the form? While the techniques and ideas that appear thus far in the listings certainly work, <font color="#800000" size="4"><strong><em>it would be simpler yet if the form were the service</em></strong></font> and hosted itself. For this to work, the form (or any window) must be a singleton service. The reason is that singleton is the only instancing mode that enables you to provide WCF with a live instance to host. In addition, you would not want a per-call form that exists only during a client call (which is usually very brief), nor would you want a per-session form that only a single client can establish a session with and update.
<p>When a form is also a service, <font color="#800000" size="4"><strong><em>having that form as a singleton service is the best instancing mode all around</em></strong></font>.</p>
</blockquote>
<p>I think that this article serves as a great treatise leading to only one conclusion &#8211; you&#8217;d have to be crazy to try to do this without some higher level framework, preferably with a different low-level framework too <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  . Sucks Microsoft didn&#8217;t put one out &#8211; nor is there a pending beta, CTP, or even word about some project with a codename handling this. From what I know about <a href="http://www.codeplex.com/prism">Prism</a>, it doesn&#8217;t intend to handle this issue either.
<p>One thing that isn&#8217;t covered in the article is that if you do choose not to tie the client-side service to the UI thread, you open yourself up to race conditions. Reasons you&#8217;d want to handle messages on a different thread center around UI responsiveness. I&#8217;ve written about these things before:
<ul>
<li>
<h4><a href="http://udidahan.weblogs.us/2007/12/06/object-builder-the-place-to-fix-system-wide-threading-bugs/">Object Builder &#8211; the place to fix system-wide threading bugs</a></h4>
</li>
<li>
<h4><a href="http://udidahan.weblogs.us/2007/12/07/eureka-aop-is-the-final-piece-of-the-multi-threaded-smart-client-puzzle/">Eureka! AOP is the final piece of the multi-threaded smart client puzzle</a></h4>
</li>
<li>
<h4><a href="http://udidahan.weblogs.us/2007/12/26/what-makes-smart-clients-safe/">What Makes Smart Clients Safe?</a></h4>
</li>
</ul>
<p>The more I read things like this, the more I feel that I have to get going with my nServiceBus based solution. I&#8217;m fairly swamped as it is, so if anyone is interested in helping get this project off the ground, I&#8217;d be most grateful &#8211; as I think anyone else that had to build a smart client would. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2008/04/11/wcf-smart-clients-and-deadlocks/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>[Podcast] Message Ordering: Is it Cost Effective?</title>
		<link>http://www.udidahan.com/2008/01/01/podcast-message-ordering-is-it-cost-effective/</link>
		<comments>http://www.udidahan.com/2008/01/01/podcast-message-ordering-is-it-cost-effective/#comments</comments>
		<pubDate>Tue, 01 Jan 2008 23:01:16 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Ask Udi Podcast]]></category>
		<category><![CDATA[Autonomous Services]]></category>
		<category><![CDATA[EDA]]></category>
		<category><![CDATA[ESB]]></category>
		<category><![CDATA[MSMQ]]></category>
		<category><![CDATA[NServiceBus]]></category>
		<category><![CDATA[Pub/Sub]]></category>
		<category><![CDATA[SOA]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2008/01/01/podcast-message-ordering-is-it-cost-effective/</guid>
		<description><![CDATA[In this podcast we&#8217;ll be discussing the issues around multi-threaded processing of messages by a service, specifically that the processing of message received second may be finished before that of the first. This scenario tends to rear its ugly head at higher levels of load and is critical for correctness in high-scalability environments.
Our long time [...]]]></description>
			<content:encoded><![CDATA[<p>In this podcast we&#8217;ll be discussing <span class="greenBlurb">the issues around multi-threaded processing of messages by a service, specifically that the processing of message received second may be finished before that of the first. This scenario tends to rear its ugly head at higher levels of load and is critical for correctness in high-scalability environments.</span></p>
<p>Our long time listener Bill asks:</p>
<blockquote><p> Hi Udi,</p>
<p>I have a question  around processing of messages in proper order.  When leveraging multiple  threads to process messages in a message queue, it is possible for the  second message in the queue to get processed before the first &#8211; especially  if the first message is considerably larger than the second.  I have taken  a lot of care to make sure that messages are sent in the correct order, only to  find that the receiving system can process them out of order  anyway.</p>
<p>Consider a  Policy Created notification, which must come before a Policy Approved  notification.  If both messages are sitting in the queue when the receiving  service starts up, the approval message can be processed before the creation  message. How can I make sure that message ordering is respected by the receiving  system?  I am using WCF/MSMQ as the underlying transport by the way.   The only way I have found so far is to limit the receiving service to a single  thread, which is by no means desirable.</p>
<p>Best  Regards,</p>
<p>Bill</p></blockquote>
<h3>Download</h3>
<p><a href="http://www.ddj.com/architect/205206017">Download via the Dr. Dobb&#8217;s site</a></p>
<p>Or download directly <a href="http://www.dobbsprojects.com/media/newengine/dynamp.php/071231ud01.mp3?podcast=071231ud01.mp3">here</a>.</p>
<h3>Additional References</h3>
<ul>
<li>Blog post: <a href="http://udidahan.weblogs.us/2007/12/09/in-order-messaging-a-myth/">In-Order Messaging a Myth?</a></li>
<li>Blog post: <a href="http://udidahan.weblogs.us/2007/12/15/handling-messages-out-of-order/">Handling Messages out of Order</a></li>
</ul>
<h3>Want more?</h3>
<p>Check out the <a href="/ask-udi/">“Ask Udi”</a> archives.</p>
<h3>Got a question?</h3>
<p><a href="mailto:podcast@UdiDahan.com">Send Udi your question to answer on the show.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2008/01/01/podcast-message-ordering-is-it-cost-effective/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
<enclosure url="http://www.dobbsprojects.com/media/newengine/dynamp.php/071231ud01.mp3?podcast=071231ud01.mp3" length="0" type="audio/mp3" />
		</item>
		<item>
		<title>What Makes Smart Clients Safe?</title>
		<link>http://www.udidahan.com/2007/12/26/what-makes-smart-clients-safe/</link>
		<comments>http://www.udidahan.com/2007/12/26/what-makes-smart-clients-safe/#comments</comments>
		<pubDate>Wed, 26 Dec 2007 07:42:13 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Smart Client]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/12/26/what-makes-smart-clients-safe/</guid>
		<description><![CDATA[ After my recent post on using AOP for smart client development, my partner-in-crime, Arnon, suggested I explain a little bit more on the whole issue of multi-threading in the UI. This isn&#8217;t going to be another tired explanation of how you should only update controls on the main thread. This is going to be [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://udidahan.weblogs.us/wp-content/uploads/doctor-motion2.jpg"><img src="http://udidahan.weblogs.us/wp-content/uploads/doctor-motion2-thumb.jpg" style="border-width: 0px; margin: 0px 20px 20px" alt="doctor_motion2" align="right" border="0" height="244" width="150" /></a> After my <a href="http://udidahan.weblogs.us/2007/12/07/eureka-aop-is-the-final-piece-of-the-multi-threaded-smart-client-puzzle/">recent post</a> on using AOP for smart client development, my partner-in-crime, <a href="http://www.rgoarchitects.com/nblog/default.aspx">Arnon</a>, suggested I explain a little bit more on the whole issue of multi-threading in the UI. This isn&#8217;t going to be another tired explanation of how you should only update controls on the main thread. This is going to be a post on the challenges multi-threading brings and how to address them.</p>
<h3>Multiple Threads &#8211; Why?</h3>
<p>One of the properties of smart clients is that they should be able to work offline. Sometimes that means an explicit action of taking data and bringing it to the local machine so that the user can work on it, and other times it just has to do with the fact that wireless connectivity can be flaky. More interesting scenarios include the submission of batch jobs and receiving notification on when they complete. The bottom line is that the user should be able to continue doing their interactive work uninterrupted as all this is occurring.</p>
<p>While the user is disconnected, obviously the data they are working on is local &#8211; the client is not calling the server to perform the work on its behalf. However, in the flaky connectivity scenario, this happens all the time. In other words, the design should be the same for handling all scenarios. One thread for interacting with the user, and (at least) on other thread for handling the issues of connectivity. The one thing that is clear is that we are going to have data on the client with which the user interacts on one thread, and which the background thread will also be updating as notifications arrive from the server.</p>
<h3>Local Data and Multi-Threading &#8211; a Recipe for Disaster</h3>
<p>When multiple threads are working with the same data, unless some specific code is in that object to make it thread-safe, there&#8217;s a good chance that object will end up in an inconsistent state. This can be catastrophic if we&#8217;re talking about air traffic control systems, dispensing medication, factory floor automation, etc. The problem is that we can&#8217;t just lock down the entire system whenever something needs to be done. While in some cases I&#8217;ve seen projects make each object thread-safe, implementing some base class for handling locking, that doesn&#8217;t work between objects and results in deadlocks.</p>
<p>Just as an example of the multi-object problem, consider the doctor prescribing medication for a patient. Now, the data about a patient in a smart client is not all on the Patient Object &#8211; there are lists of connected test results, medication already being taken, which nurses and doctors have treated this patient so far, etc. As a test result gets pushed to the client from the server, a new doctor unfamiliar with the history of the patient orders the same test again. These two objects under Patient &#8211; TestRequest and TestResult are being acted upon by different threads. One of the goals of the system was to eliminate duplicate testing for patients &#8211; cited as costing the hospital chain millions of dollars a year. Good thing we addressed the cross-object multi-threaded locking thing properly <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h3>Always Switch from Background to Foreground?</h3>
<p>One solution I&#8217;ve seen used successfully is to always change threads from background to foreground whenever an update comes in from the server. This works when you don&#8217;t have many updates or the work performed on the client as a result of an update doesn&#8217;t take long. Always keep in mind, though, the flaky connectivity scenario. What tends to happen is that server notifications bunch up and then hit the client all together. When this occurs, clients developed this way are rendered unusable.</p>
<p>It would seem like this solution isn&#8217;t valid because of the above, but don&#8217;t dismiss it so quickly. This is an easy solution to implement that may address your specific environment and, as such, be cost effective. A large part of the work I&#8217;ve been doing is to make the more complex environments just as easy to develop as these simpler ones.</p>
<h3>Infrastructure-level, Safe, Multi-Object Locking</h3>
<p>Luckily for us developers, in the .net framework there is a class that handles this for us &#8211; well, 2 actually: <a href="http://msdn2.microsoft.com/en-us/library/system.contextboundobject(VS.90).aspx">ContextBoundObject</a> and <a href="http://msdn2.microsoft.com/en-us/library/system.runtime.remoting.contexts.synchronizationattribute.aspx">SynchronizationAttribute</a>. When using these two classes, we can create something known as a <a href="http://www.ddj.com/architect/184405771">Synchronization Domain</a> which acts as a global lock for all objects belonging to the synchronization domain. What this means is that if the user thread is trying to add a test request object while the background thread is already creating a test result object, the user thread will block automatically until the background thread completes its work.</p>
<p>There is only one teensy-weensy problem &#8211; ContextBoundObjects are really heavy-weight. The last thing you want is having millions of these running around in your client &#8211; you&#8217;ll end up with a multi-threading safe unusable UI. Also, the creation of an object inheriting from ContextBoundObject takes quite a bit longer than a plain-old.net object. In other words, technology by itself will not solve our problems &#8211; we need some patterns for the correct use of the technology so that we can maintain a reasonable level of performance while taking care of safety.</p>
<h3>MVC and Threading &#8211; Controllers</h3>
<p>Regardless of which flavour of MVC you prefer (I&#8217;m in the Supervising Controller camp for smart clients), the logic controlling what goes on in the client is found in the controllers. What this means is that actions from the user as well as background notifications will need to go through these controllers. It is important that these controllers be thread-safe since they are state-full &#8211; managing which windows are open, which step in a given process a user is currently doing, etc.</p>
<p>The characteristics of these controller objects which make them best suited to inherit from ContextBoundObject are that there are only a handful of these objects at any point in time and that they are created at startup &#8211; they&#8217;re singletons (in the &#8220;only-one-of-them&#8221; sense of the word).</p>
<p>The only special thing that controllers need to do in terms of threading is to dispatch calls to view objects on the foreground thread, even if the thread currently running is the background thread. For example, popping up a &#8220;toast&#8221; that a test result has arrived when a notification from the server comes in.</p>
<p>These elements &#8211; inheriting from ContextBoundObject, use of the SynchronizationAttribute, and thread-switching can be pulled up in to a BaseController class:</p>
<div style="overflow: scroll; width: 100%">
<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; }</p>
<p>.csharpcode .rem { color: #008000; }</p>
<p>.csharpcode .kwrd { color: #0000ff; }</p>
<p>.csharpcode .str { color: #006080; }</p>
<p>.csharpcode .op { color: #0000c0; }</p>
<p>.csharpcode .preproc { color: #cc6633; }</p>
<p>.csharpcode .asp { background-color: #ffff00; }</p>
<p>.csharpcode .html { color: #800000; }</p>
<p>.csharpcode .attr { color: #ff0000; }</p>
<p>.csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; }</p>
<p>.csharpcode .lnum { color: #606060; }</style>
<pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.ComponentModel;
<span class="kwrd">using</span> System.Runtime.Remoting.Contexts;

<span class="kwrd">namespace</span> ControllerFramework
{
    [Synchronization(SynchronizationAttribute.REQUIRED)]
    <span class="kwrd">public</span> <span class="kwrd">class</span> BaseController : ContextBoundObject
    {
        <span class="kwrd">protected</span> ISynchronizeInvoke invoker;
        <span class="kwrd">public</span> ISynchronizeInvoke Invoker
        {
            get { <span class="kwrd">return</span> invoker; }
            set { invoker = <span class="kwrd">value</span>; }
        }

        <span class="kwrd">protected</span> <span class="kwrd">void</span> MarshalToUiThread(Delegate toCall, <span class="kwrd">params</span> <span class="kwrd">object</span>[] parameters)
        {
            <span class="kwrd">if</span> (<span class="kwrd">this</span>.invoker == <span class="kwrd">null</span>)
                <span class="kwrd">return</span>;

            <span class="kwrd">if</span> (<span class="kwrd">this</span>.invoker.InvokeRequired)
                invoker.BeginInvoke(toCall, parameters);
            <span class="kwrd">else</span>
                toCall.DynamicInvoke(parameters);
        }
    }
}</pre>
</div>
<p>Well, I think that this is long enough for a single blog post. In the next instalment of this series I&#8217;ll be talking about how model objects and views fit into the multi-threaded smart client. After that, we&#8217;ll be seeing how service agents, messaging, and service contract design need to be done in this style. While all this blogging will be going on, I&#8217;ll be getting a software factory up that will tie all these patterns and frameworks together so that all developers will be able to write thread-safe, high-performance smart clients without needing a doctorate in computer science &#8211; not that I have one <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Questions? Comments? Thoughts?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/12/26/what-makes-smart-clients-safe/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Handling messages out of order</title>
		<link>http://www.udidahan.com/2007/12/15/handling-messages-out-of-order/</link>
		<comments>http://www.udidahan.com/2007/12/15/handling-messages-out-of-order/#comments</comments>
		<pubDate>Sat, 15 Dec 2007 23:22:24 +0000</pubDate>
		<dc:creator>udidahan</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Availability]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[EDA]]></category>
		<category><![CDATA[NServiceBus]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/12/15/handling-messages-out-of-order/</guid>
		<description><![CDATA[I wanted to follow up on my recent post, &#8220;In order messaging a myth?&#8221; by showing the exact code that solves the issue. I have a podcast waiting to come online that deals with the specifics, so keep your eye out for that too.
The important thing to note is that if we just automatically return [...]]]></description>
			<content:encoded><![CDATA[<p>I wanted to follow up on my recent post, &#8220;<a href="http://udidahan.weblogs.us/2007/12/09/in-order-messaging-a-myth/">In order messaging a myth?</a>&#8221; by showing the exact code that solves the issue. I have a podcast waiting to come online that deals with the specifics, so keep your eye out for that too.</p>
<p>The important thing to note is that if we just automatically return the message to the queue, we may get &#8220;stuck&#8221; with that message if the first PolicyCreatedMessage never arrived. This opens us up to a Denial-of-Service attack by quite simply flooding us with a bunch of messages that never get cleaned up.</p>
<p>Anyway, the general idea is to first try the regular happy path, and only if we see that prerequisite data isn&#8217;t available, do we see if another thread may be working on that data. This is done by decreasing the isolation level of our transaction from the regular ReadCommitted to ReadUncommitted. This will enable our thread to see if some other thread inserted the policy in to the Policies table but hasn&#8217;t committed its transaction yet.</p>
<div style="overflow: auto; ">
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">public</span> <span style="COLOR: blue">class</span> <span style="COLOR: #2b91af">PolicyApprovedMessageHandler</span> : BaseDBMessageHandler&lt;PolicyApprovedMessage&gt;<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </span>{<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">public</span> <span style="COLOR: blue">override</span> <span style="COLOR: blue">void</span> Handle(PolicyApprovedMessage message)<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>{<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">bool</span> policyExists = <span style="COLOR: blue">true</span>;<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><o:p><font size="3">&nbsp;</font></o:p></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">using</span> (<span style="COLOR: #2b91af">ISession</span> s = OpenSession())<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">using</span> (<span style="COLOR: #2b91af">ITransaction</span> tx = s.BeginTransaction(<span style="COLOR: #2b91af">IsolationLevel</span>.ReadCommitted))<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>{<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>Policy p = s.Get&lt;Policy&gt;(message.PolicyId);<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><o:p><font size="3">&nbsp;</font></o:p></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">if</span> (p != <span style="COLOR: blue">null</span>)<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>{<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>p.Approve();<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>tx.Commit();<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>}<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">else<o:p></o:p></span></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>policyExists = <span style="COLOR: blue">false</span>;<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>}<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><o:p><font size="3">&nbsp;</font></o:p></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">if</span> (!policyExists) <span style="COLOR: green">// check to make sure<o:p></o:p></span></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">using</span> (<span style="COLOR: #2b91af">ISession</span> s = OpenSession())<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="mso-spacerun: yes">&nbsp;</span><span style="COLOR: blue">using</span> (<span style="COLOR: #2b91af">ITransaction</span> tx = s.BeginTransaction(<span style="COLOR: #2b91af">IsolationLevel</span>.ReadUncommitted))<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>{<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>Policy p = s.Get&lt;Policy&gt;(message.PolicyId);<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><o:p><font size="3">&nbsp;</font></o:p></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">if</span> (p != <span style="COLOR: blue">null</span>) <span style="COLOR: green">// another thread hasn&#8217;t committed its tx yet, so try message again later<o:p></o:p></span></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">this</span>.bus.HandleCurrentMessageLater();<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">else<o:p></o:p></span></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span><span style="COLOR: blue">this</span>.bus.Return((<span style="COLOR: blue">int</span>)ErrorCodes.PolicyNotFound);<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>}<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 0pt; LINE-HEIGHT: normal; mso-layout-grid-align: none"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>}<o:p></o:p></font></span></p>
<p class="MsoNormal" style="MARGIN: 0cm 0cm 10pt"><span style="FONT-FAMILY: Consolas; mso-bidi-font-family: 'Times New Roman'; mso-no-proof: yes"><font size="3"><span style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </span>}</font></span><span style="FONT-SIZE: 9pt; LINE-HEIGHT: 115%"><o:p></o:p></span></p>
</div>
<p>The next step will be how we take this code and make it generic, so that we don&#8217;t have write the same code over and over again for the different kinds of message handlers we have.</p>
<p>But that will have to wait until the next installment <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/12/15/handling-messages-out-of-order/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Eureka! AOP is the final piece of the multi-threaded smart client puzzle</title>
		<link>http://www.udidahan.com/2007/12/07/eureka-aop-is-the-final-piece-of-the-multi-threaded-smart-client-puzzle/</link>
		<comments>http://www.udidahan.com/2007/12/07/eureka-aop-is-the-final-piece-of-the-multi-threaded-smart-client-puzzle/#comments</comments>
		<pubDate>Fri, 07 Dec 2007 23:01:50 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[AOP]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[NServiceBus]]></category>
		<category><![CDATA[Smart Client]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/12/07/eureka-aop-is-the-final-piece-of-the-multi-threaded-smart-client-puzzle/</guid>
		<description><![CDATA[If you&#8217;ve read my recent post on the threading issues I&#8217;ve been dealing with in Smart Client Applications, then you&#8217;re probably beginning to get the picture that its fairly complex. To tell you the truth, it is. And up until this point I haven&#8217;t been able to find anything that&#8217;ll help &#8211; and that includes [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve read my recent post on the <a href="http://udidahan.weblogs.us/2007/12/06/object-builder-the-place-to-fix-system-wide-threading-bugs/">threading issues I&#8217;ve been dealing with in Smart Client Applications</a>, then you&#8217;re probably beginning to get the picture that its fairly complex. To tell you the truth, it is. And up until this point I haven&#8217;t been able to find anything that&#8217;ll help &#8211; and that includes the CAB/SCSF. But yesterday I had my epiphany. The answer was in AOP.</p>
<p>You see, the main problem that I hadn&#8217;t been able to solve was that in order for the code to be thread-safe, you had to make sure that no code in the views would/could change entity data. One solution is not to use data-binding, which sucks, but isn&#8217;t enough to be sure. Another solution is to have all supervising-controllers clone an entity before they give it to a view. Even if you could possibly code review every line of those classes, the new guy (or old guy who forgot) will, by accident, write one new line of code that could pass an entity to a view without cloning it first. That&#8217;s not a very sustainable solution.</p>
<p>This thing has been bothering me for a couple of months now and I hadn&#8217;t found a way around it. Until yesterday, like I said. I was talking to somebody about threading stuff, and somehow my unconscience lobbed me this thought about AOP. Now I&#8217;m not the sharpest pencil in the pack, but I know to listen when my unconscience &#8220;speaks&#8221;.</p>
<p>So I set about going over what I knew about AOP &#8211; interceptors, advisors, advice, introductions, etc, etc. And then it dawned on me. I could intercept all calls to any object that implemented IView, check the parameters of those calls, and if they implemented IEntity, to clone them before passing them through.</p>
<p>&lt;Homer-style WOOHOO /&gt;</p>
<p>The great thing is that developers don&#8217;t need to remember to clone entities &#8211; it happens automatically. The even greater thing is that this will lead developers to writing the correct kind of interaction between their views and supervising controllers.</p>
<p>Together with <a href="http://www.nServiceBus.com">nServiceBus</a>, this is going to make the extremely difficult problem of writing thread-safe smart clients possible. </p>
<p>I&#8217;ve never made use of AOP in a framework before so I&#8217;d like to get the broader community&#8217;s feedback on this before incorporating this in production. I&#8217;ve spoken with some serious AOP folks who have allayed most of my uncertainties, but I&#8217;d like to hear more. Anyway, here&#8217;s the <a href="http://udidahan.weblogs.us/wp-content/uploads/aoptest.zip">proof of concept</a> (that makes use of <a href="http://www.springframework.net">Spring</a>). </p>
<p>If this turns out to be a viable solution, I think we&#8217;ll have a solid environment for building a software factory on top of. That is something that I&#8217;m really excited about. In this multi-core future (present) that is upon us, multi-threading on the client is pretty much a necessity. We need a way to get things safe and stable by default without requiring a member of the CLR team to hold our hand.</p>
<p>Anybody who&#8217;s interested in helping, drop a comment below.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/12/07/eureka-aop-is-the-final-piece-of-the-multi-threaded-smart-client-puzzle/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Object Builder &#8211; the place to fix system-wide threading bugs</title>
		<link>http://www.udidahan.com/2007/12/06/object-builder-the-place-to-fix-system-wide-threading-bugs/</link>
		<comments>http://www.udidahan.com/2007/12/06/object-builder-the-place-to-fix-system-wide-threading-bugs/#comments</comments>
		<pubDate>Thu, 06 Dec 2007 10:38:59 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[NServiceBus]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Scalability]]></category>
		<category><![CDATA[Smart Client]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/12/06/object-builder-the-place-to-fix-system-wide-threading-bugs/</guid>
		<description><![CDATA[Last week I was at a client in their test lab and saw a strange bit of behavior. The system could be described as something like an air traffic control system, showing things moving around on a map. For just a second, a fraction of a second, one of the &#8220;planes&#8221; disappeared from the map [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I was at a client in their test lab and saw a strange bit of behavior. The system could be described as something like an air traffic control system, showing things moving around on a map. For just a second, a fraction of a second, one of the &#8220;planes&#8221; disappeared from the map and then reappeared again. </p>
<p>When I asked if anybody else saw it, one of the developers said, &#8220;Yeah, that happens sometimes &#8211; but it fixes itself right after that.&#8221;</p>
<p>&#8220;What if the user sends a command to the server making use of that location?&#8221;, the PM asked. &#8220;Could that cause them to collide?&#8221;</p>
<p>You could hear a pin drop.</p>
<p>After everyone got passed the preliminary shock, we got down to work. I asked if I could look at the logs, but after more than an hour, I found nothing. No reason to explain the strange behavior. I suggested doing some more instrumentation so that whenever a location changed on the client-side entities, we&#8217;d write that to the log.</p>
<p>After that, we ran the system again in the lab under the expected load (several hundred things moving every second, and the user doing the expected activity) and didn&#8217;t notice anything. An intern &#8220;volunteered&#8221; to keep working the system while the rest of us went to lunch. When we came back, he told us that everything seemed to be working OK.</p>
<p>These <a href="http://en.wikipedia.org/wiki/Heisenbug#Heisenbugs">Heisenbugs</a> are the things that keep me up at night. </p>
<p>&#8220;Watching the system changes its behavior&#8221;, one of the older devs nodded his head sagely.</p>
<p>Just as we were about to leave the lab another one of the developers gave a shout, &#8220;It did it again!&#8221;. We quickly stopped the system. Opened the (rather huge) log files and looked for the latest entries.</p>
<p>There it was.</p>
<p>A context switch between setting the latitude and longitude of an entity.</p>
<p>That should not have happened. Not that context switches don&#8217;t happen, but rather that it should have been impossible by design. We had made use of synchronization domains and the appropriate patterns so that two threads could never concurrently be working on the same instance of an entity. The synchronization features baked in to <a href="http://www.nServiceBus.com">nServiceBus</a> had taken care of everything up to that point.</p>
<p>Before getting into the threading solution, I want to address a specific alternate patch that was deployed in the meantime:</p>
<p>The solution for the long/lat problem was simple &#8211; just make Location a value object and use a single setter for it rather than one for Latitide and another for Longitude. We were still worried about other bits of data that were correllated in the domain &#8211; things that couldn&#8217;t be solved the same way. </p>
<p>After getting 3 grizzled C++ veterans in the room, we did a code walkthrough of the threading model of nServiceBus. We went through the nitty gritty details of synchronization domains, how the Bus object was outside of the domain, why that was important for user experience, how the message handlers couldn&#8217;t be ContextBoundObjects because of the performance impact of creating and destroying them at a high rate, why they couldn&#8217;t just be singletons, why they still had to run in the synchronization domain, so that the UI thread couldn&#8217;t work on the same (or related) objects at the same time, etc, etc.</p>
<p>And then it hit me.</p>
<p>The bus was communicated directly with the message handlers.</p>
<p>After the Object Builder created the message handler, the bus dispatched the message to the handler directly. And since the bus was outside the synchronization domain, then the thread calling into the handler wouldn&#8217;t have locked the domain, leaving the UI thread open to go in and touch those very same objects.</p>
<p>They say that really understanding the problem is 90% of the solution. I&#8217;m hoping to meet them some day, because they&#8217;re really smart.</p>
<p>All that we needed to do was have the Object Builder dispatch the message to the handler instead of the bus &#8211; since the builder was configured to be in the synchronization domain (on the client side). Something as simple as just adding the method:</p>
<div style="border-right: black 1px solid; padding-right: 1em; border-top: black 1px solid; padding-left: 1em; padding-bottom: 0em; overflow: auto; border-left: black 1px solid; padding-top: 0em; border-bottom: black 1px solid; font-family: courier; background-color: beige">
void BuildAndDispatch(Type typeToBuild, string methodName, params object[] methodArgs);
</div>
<p>So, instead of the bus using this code:</p>
<div style="border-right: black 1px solid; padding-right: 1em; border-top: black 1px solid; padding-left: 1em; padding-bottom: 0em; overflow: auto; border-left: black 1px solid; padding-top: 0em; border-bottom: black 1px solid; font-family: courier; background-color: beige">
object handler = this builder.Build(messageHandlerType);<br />
MethodInfo method = messageHandlerType.GetMethod(&#8221;Handle&#8221;);<br />
method.Invoke(handler, messageToBeDispatched);
</div>
<p>It would do:</p>
<div style="border-right: black 1px solid; padding-right: 1em; border-top: black 1px solid; padding-left: 1em; padding-bottom: 0em; overflow: auto; border-left: black 1px solid; padding-top: 0em; border-bottom: black 1px solid; font-family: courier; background-color: beige">
this.builder.BuildAndDispatch(messageHandlerType, &#8220;Handle&#8221;, messageToBeDispatched);
</div>
<p>[Just FYI, this is now up on the <a href="http://sourceforge.net/projects/nservicebus">sourceforge site</a>]</p>
<p>We redeployed the system to the lab, ran all the functional, stress, load, etc tests and everything appeared to be stable. The system has been under scrutiny for the past 4 days by batteries of testers instructed specifically to look for those strage kinds of behavior. Other developers are running scripts on the log files looking for other kinds of context switches that may have been missed by the testers. I am happy to report that they haven&#8217;t found anything.</p>
<p>Not that this means that the problem isn&#8217;t there. We really can&#8217;t be sure. However, the PM has decided that we are stable enough to go into pilot mode &#8211; deploying into production beside the current system; having users work on both systems at the same time. I&#8217;m optimistic.</p>
<p>I&#8217;m personally involved in two more production-projects that are making use of <a href="http://www.nServiceBus.com">nServiceBus</a> in similarly high-end situations and we&#8217;ve never had these threading problems &#8211; now two years running.</p>
<p>That was an interesting week.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/12/06/object-builder-the-place-to-fix-system-wide-threading-bugs/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>[Podcast] Thread-Safe Asynchronous Smart Clients</title>
		<link>http://www.udidahan.com/2007/10/12/podcast-thread-safe-asynchronous-smart-clients/</link>
		<comments>http://www.udidahan.com/2007/10/12/podcast-thread-safe-asynchronous-smart-clients/#comments</comments>
		<pubDate>Fri, 12 Oct 2007 07:08:09 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Ask Udi Podcast]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Smart Client]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/10/12/podcast-thread-safe-asynchronous-smart-clients/</guid>
		<description><![CDATA[In this podcast we&#8217;ll look at various patterns involved in creating MVC-based Smart Clients which communicate using asynchronous messaging and how to avoid threading problems there. 
Neil asks:

Hi Udi,
We&#8217;re building a smart client application that uses WCF for full-duplex communications with our server. This is the asynchronous communication you talk about in your podcast. The [...]]]></description>
			<content:encoded><![CDATA[<p>In this podcast we&#8217;ll look at various patterns involved in creating MVC-based Smart Clients which communicate using asynchronous messaging and how to avoid threading problems there. </p>
<p>Neil asks:</p>
<blockquote><p>
Hi Udi,</p>
<p>We&#8217;re building a smart client application that uses WCF for full-duplex communications with our server. This is the asynchronous communication you talk about in your podcast. The smart-client is based on the MVC pattern, where model objects raise events when they&#8217;re changed so that the views can update themselves.</p>
<p>What&#8217;s started happening recently is that the smart-client has been freezing-up on us intermittently. We don&#8217;t know how to debug this and are wondering if its an architectural problem.</p>
<p>Any help you can give would be most appreciated.</p>
<p>Neil
</p></blockquote>
<p><b>Download</b></p>
<p><a href="http://www.ddj.com/architect/202401468">Download via the Dr. Dobb&#8217;s site</a></p>
<p>Or download directly <a href="http://www.dobbsprojects.com/media/newengine/dynamp.php/071011ud01.mp3?podcast=071011ud01.mp3">here</a></p>
<p><b>Additional References</b></p>
<ul>
<li>Blog post on <A href="http://udidahan.weblogs.us/2007/04/04/occasionally-connected-systems-architecture/">Occasionally Connected Systems Architecture</A></li>
<li>Blog post on <A href="http://udidahan.weblogs.us/2007/09/28/objectbuilder-synchronization-features-needed-for-pubsub-ing-smart-clients/">ObjectBuilder synchronization features needed for pub/sub-ing Smart Clients</A></li>
</ul>
<p><b>Want more?</b></p>
<p>Check out the <a href="/ask-udi/">&#8220;Ask Udi&#8221; archives</a>.</p>
<p><b>Got a question?</b></p>
<p><a href="mailto:podcast@UdiDahan.com">Send Udi your question to answer on the show.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/10/12/podcast-thread-safe-asynchronous-smart-clients/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
<enclosure url="http://www.dobbsprojects.com/media/newengine/dynamp.php/071011ud01.mp3?podcast=071011ud01.mp3" length="13030892" type="audio/mp3" />
		</item>
		<item>
		<title>ObjectBuilder synchronization features needed for pub/sub-ing Smart Clients</title>
		<link>http://www.udidahan.com/2007/09/28/objectbuilder-synchronization-features-needed-for-pubsub-ing-smart-clients/</link>
		<comments>http://www.udidahan.com/2007/09/28/objectbuilder-synchronization-features-needed-for-pubsub-ing-smart-clients/#comments</comments>
		<pubDate>Fri, 28 Sep 2007 21:36:58 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Pub/Sub]]></category>
		<category><![CDATA[Smart Client]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/09/28/objectbuilder-synchronization-features-needed-for-pubsub-ing-smart-clients/</guid>
		<description><![CDATA[I&#8217;ve been getting some questions from the Dependency Injection folks out there as to why I have my own Object Builder wrapping the framework. There are two very good reasons why I do this:
The first is to insulate the framework and application code that I write from the choice of one dependency injection technology or [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been getting some questions from the Dependency Injection folks out there as to why I have my own Object Builder wrapping the framework. There are two very good reasons why I do this:</p>
<p>The first is to insulate the framework and application code that I write from the choice of one dependency injection technology or another. I want the ability to switch easily from one to the other &#8211; not so much that projects go back and forth. Updating those config files is definitely <i>not</i> easy. However, it allows me to have &#8220;portable&#8221; framework code that is applicable to all the projects I consult on, regardless of their choice of technology.</p>
<p>The second has to do with <a href="http://udidahan.weblogs.us/category/nservicebus/">NServiceBus</a> specifically. In order to make use of duplex communication on smart clients, you need a background thread. That thread will be updating the same (model) objects as the UI thread. That means we need synchronization. I prefer to use .NET&#8217;s built-in synchronization domains in order to solve this rather thorny problem.</p>
<p>The only thing is that message handlers need to be in the synchronization domain so that they can easily update those objects. However, the Bus object must not be in the synchronization domain so that if we&#8217;ve received a large update from the server, we won&#8217;t be locking out the UI thread from interacting with data on the client. </p>
<p>Since the bus makes use of a dependency injection framework to create message handlers, this was the best place to put the code which causes message handlers to run within the synchronization domain.</p>
<p>Be aware that in order to enjoy this feature, you need to split up those large server updates into multiple, logical objects (that implement IMessage), but you can still publish them all in one go using the method: </p>
<p>void Publish(params IMessage[] messages);</p>
<p>And, of course, you need to set the JoinSynchronizationDomain property of the Object Builder.</p>
<p>I&#8217;ll have a podcast coming out on this topic soon.</p>
<p>You can get the code here:</p>
<p><a href='http://udidahan.weblogs.us/wp-content/uploads/objectbuilder.zip' title='Object Builder.zip'>Object Builder.zip</a></p>
<p>But you&#8217;ll have to get the Spring Framework code from the <a href="http://springframework.net/">official site</a>. Make sure you download <a href="http://sourceforge.net/project/showfiles.php?group_id=106751">RC 1.1</a>. Then, take the binaries and copy them to the &#8220;BIN&#8221; folder of the Object Builder solution. If you&#8217;re looking to save on some &#8220;weight&#8221;, you only need &#8220;Spring.Core.dll&#8221;, &#8220;Common.Logging.dll&#8221; and &#8220;antlr.runtime.dll&#8221; for the solution to compile. You will need one of the logging implementations DLLs to get anything written to a log, obviously.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/09/28/objectbuilder-synchronization-features-needed-for-pubsub-ing-smart-clients/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Fetching Strategy NHibernate Implementation Available</title>
		<link>http://www.udidahan.com/2007/09/16/fetching-strategy-nhibernate-implementation-available/</link>
		<comments>http://www.udidahan.com/2007/09/16/fetching-strategy-nhibernate-implementation-available/#comments</comments>
		<pubDate>Mon, 17 Sep 2007 00:54:02 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[ADO.NET]]></category>
		<category><![CDATA[Caching]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/09/16/fetching-strategy-nhibernate-implementation-available/</guid>
		<description><![CDATA[A couple of months ago I put out a post discussing one way to implement custom fetching strategies. Anyway, I finally got around to putting my money where my mouth was&#8230;
So, I&#8217;ve implemented the pattern in NHibernate, adding the following method to ISession:
T Create&#60;T&#62;();
As well as adding the following interface to the NHibernate package:

  [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of months ago I put out a <a href="http://udidahan.weblogs.us/2007/04/23/fetching-strategy-design/">post discussing one way to implement custom fetching strategies</a>. Anyway, I finally got around to putting my money where my mouth was&#8230;</p>
<p>So, I&#8217;ve implemented the pattern in NHibernate, adding the following method to ISession:</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:550; font-family:courier">T Create&lt;T&gt;();</div>
<p>As well as adding the following interface to the NHibernate package:</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:550; font-family:courier">
    public interface IFetchingStrategy&lt;T&gt;<br />
    {<br />
        ICriteria AddFetchJoinTo(ICriteria criteria);<br />
    }
</div>
<p>All this enables you to have a stronger separation between your service layer classes and your domain model class, as well as for you to express each service-level use case as a domain concept &#8211; an interface.</p>
<p>Once you have such an interface, you can create a fetching strategy for that use case and define exactly how deep of an object graph you want to load so that you only hit the DB once for that use case.</p>
<p>The nice thing is that its all configured with Spring. In other words, if you the entry for your fetching strategy class exists, you get the improved performance, if it doesn&#8217;t, you don&#8217;t. All without touching your service layer classes.</p>
<p>Just as an example, when I&#8217;m in the use case modeled by &#8220;ICustomer&#8221;, I want to get all the customer&#8217;s orders, and their orderlines. This would be done by having a class like this:</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:550; font-family:courier">
    public class CustomerFetchingStrategy : IFetchingStrategy&lt;ICustomer&gt;<br />
    {<br />
        public ICriteria AddFetchJoinTo(ICriteria criteria)<br />
        {<br />
            criteria.SetFetchMode(&#8221;orders&#8221;, FetchMode.Eager).<br />
                SetFetchMode(&#8221;orders.orderLines&#8221;, FetchMode.Eager);</p>
<p>            return criteria;<br />
        }<br />
    }
</p></div>
<p>And the configuration would look like this (as a part of the regular spring template):</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:550; font-family:courier">
      &lt;object id=&#8221;CustomerFetchingStrategy&#8221; type=&#8221;Domain.Persistence.CustomerFetchingStrategy, Domain.Persistence&#8221; /&gt;
</div>
<p>If you want to take a look at the full solution, you can find it here. For some reason, the combined file was too big for the upload on my blog so it&#8217;s split into two. Unzip both packages into the same directory. You&#8217;ll find a file called &#8220;db_scripts.sql&#8221; which contains the schema for the DB. Don&#8217;t forget to update your connection string in the &#8220;hibernate.cfg.xml&#8221;. If you&#8217;re looking for the changes I made to the NHibernate source, you can find it in the &#8220;Updated NHibernate Files&#8221; directory. The only real change is to the &#8220;SessionImpl.cs&#8221; file.</p>
<p><a href='http://udidahan.weblogs.us/wp-content/uploads/libraries.zip' title='libraries.zip'>Relevant NHibernate and Spring binaries</a>.</p>
<p><a href='http://udidahan.weblogs.us/wp-content/uploads/objectrelationalmappingdemo4.zip' title='objectrelationalmappingdemo.zip'>Source code of example</a>.</p>
<p>BTW, there is some intelligent thread-safe caching going on in SessionImpl now so that you get a much smaller performance hit (in terms of code that uses reflection) on subsequent usages of the same interfaces.</p>
<p>Let me know what you think.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/09/16/fetching-strategy-nhibernate-implementation-available/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Performant and Explicit Domain Models</title>
		<link>http://www.udidahan.com/2007/06/04/performant-and-explicit-domain-models/</link>
		<comments>http://www.udidahan.com/2007/06/04/performant-and-explicit-domain-models/#comments</comments>
		<pubDate>Mon, 04 Jun 2007 20:31:34 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Business Rules]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Data Access]]></category>
		<category><![CDATA[Databases]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Simplicity]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/06/04/performant-and-explicit-domain-models/</guid>
		<description><![CDATA[Some Technical Difficulties

Ayende and I had an email conversation that started with me asking what would happen if I added an Order to a Customer’s &#8220;Orders&#8221; collection, when that collection was lazy loaded. My question was whether the addition of an element would result in NHibernate hitting the database to fill that collection. His answer [...]]]></description>
			<content:encoded><![CDATA[<h4>Some Technical Difficulties</h4>
<p style="padding: 0em 1em;">
Ayende and I had an email conversation that started with me asking what would happen if I added an Order to a Customer’s &#8220;Orders&#8221; collection, when that collection was lazy loaded. My question was whether the addition of an element would result in NHibernate hitting the database to fill that collection. His answer was a simple &#8220;yes&#8221;. In the case where a customer can have many (millions) of Orders, that’s just not a feasible solution. The technical solution was simple – just define the Orders collection on the Customer as &#8220;inverse=true&#8221;, and then to save a new Order, just write:
</p>
<div style="border: solid black 1px; padding: 0em 1em; background-color:beige; font-family:courier; ">session.Save( new Order(myCustomer) );</div>
<p style="padding: 0em 1em;">
Although it works, it’s not &#8220;DDD compliant&#8221; <img src='http://www.udidahan.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
</p>
<p style="padding: 0em 1em;">
In Ayende’s post <a href="http://ayende.com/Blog/archive/2007/05/29/Architecting-for-Performance.aspx">Architecting for Performance</a> he quoted a part of our email conversation.  The conclusion I reached was that in order to design performant domain models, you need to know the kinds of data volumes you’re dealing with. It affects both internals and the API of the model – when can you assume cascade, and when not. It’s important to make these kinds of things explicit in the Domain Model’s API.
</p>
<h4>How do you make &#8220;transparent persistence&#8221; explicit?</h4>
<p style="padding: 0em 1em;">
The problem occurs around &#8220;transparent persistence&#8221;. If we were to assume that the Customer object added the Order object to its Orders collection, then we wouldn’t have to explicitly save orders it creates, so we would write service layer code like this:
</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:600; font-family:courier">
using (IDBScope scope = this.DbServices.GetScope(TransactionOption.On))<br />
{<br />
	IOrderCreatingCustomer c = this.DbServices.Get&lt;IOrderCreatingCustomer&gt;(msg.CustomerId);<br />
	c.CreateOrder(message.OrderAmount);</p>
<p>	scope.Complete();<br />
}
</p></div>
<p style="padding: 0em 1em;">
On the other hand, if we designed our Domain Model around the million orders constraint, we would need to explicitly save the order, so we would write service layer code like this:
</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; overflow:auto; width:600; font-family:courier">
using (IDBScope scope = this.DbServices.GetScope(TransactionOption.On))<br />
{<br />
	IOrderCreatingCustomer c = this.DbServices.Get&lt;IOrderCreatingCustomer&gt;(msg.CustomerId);<br />
	IOrder o = c.CreateOrder(message.OrderAmount);<br />
	this.DbServices.Save(o);</p>
<p>	scope.Complete();<br />
}
</p></div>
<p style="padding: 0em 1em;">
But the question remains, how do we communicate these guidelines to service layer developers from the Domain Model? There are a number of ways, but it’s important to decide on one and use it consistently. Performance and correctness require it.
</p>
<h4>Solution 1: Explicitness via Return Type</h4>
<p style="padding: 0em 1em;">
The first way is a little subtle, but you can do it with the return type of the &#8220;CreateOrder&#8221; method call. In the case where the Domain Model wishes to communicate that it handles transparent persistence by itself, have the method return &#8220;void&#8221;. Where the Domain Model wishes to communicate that it will not handle transparent persistence, have the method return the Order object created.
</p>
<p style="padding: 0em 1em;">
Another way to communicate the fact that an Order has been created that needs to be saved is with events. There are two sub-ways to do so:
</p>
<h4>Solution 2: Explicitness via Events on Domain Objects</h4>
<p style="padding: 0em 1em;">
The first is to just define the event on the customer object and have the service layer subscribe to it. It’s pretty clear that when the service layer receives a &#8220;OrderCreatedThatRequiresSaving&#8221; event, it should save the order passed in the event arguments.
</p>
<p style="padding: 0em 1em;">
The second realizes that the call to the customer object may come from some other domain object and that the service layer doesn’t necessarily know what can happen as the result of calling some method on the aggregate root. The change of state as the result of that method call may permeate the entire object graph. If each object in the graph raises its own events, its calling object will have to propagate that event to its parent – resulting in defining the same events  in multiple places, and each object being aware of all things possible with its great-grandchild objects. That is clearly bad.
</p>
<h4>What [ThreadStatic] is for</h4>
<p style="padding: 0em 1em;">
So, the solution is to use thread-static events.
</p>
<p style="padding: 0em 1em;">
[Sidebar] Thread-static events are just static events defined on a static class, where each event has the ThreadStaticAttribute applied to it. This attribute is important for server-side scenarios where multiple threads will be running through the Domain Model at the same time. The easiest thread-safe way to use static data is to apply the ThreadStaticAttribute.
</p>
<h4>Solution 3: Explicitness via Static Events</h4>
<p style="padding: 0em 1em;">
Each object raises the appropriate static event according to its logic. In our example, Customer would call:
</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; font-family:courier">
DomainModelEvents.RaiseOrderCreatedThatRequiresSavingEvent(newOrder);
</div>
<p style="padding: 0em 1em;">And the service layer would write:</p>
<div style="border: solid black 1px; background-color:beige; padding: 0em 1em; font-family:courier">
DomainModelEvents.OrderCreatedThatRequiresSaving +=<br />
	delegate(object sender, OrderEventArgs e) { this.DbServices.Save(e.Order); };
</div>
<p style="padding: 0em 1em;">
The advantage of this solution is that it requires minimal knowledge of the Domain Model for the Service Layer to correctly work with it. It also communicates that anything that doesn’t raise an event will be persisted transparently behind the appropriate root object.
</p>
<h4>Statics and Testability</h4>
<p style="padding: 0em 1em;">
I know that many of you are wondering if I am really advocating the use of statics. The problem with most static classes is that they hurt testability because they are difficult to mock out. Often statics are used as Facades to hide some technological implementation detail. In this case, the static class is an inherent part of the Domain Model and does not serve as a Facade for anything.
</p>
<p style="padding: 0em 1em;">
When it comes to testing the Domain Model, we don’t have to mock anything out since the Domain Model is independent of all other concerns. This leaves us with unit testing at the single Domain Class level, which is pretty useless unless we’re TDD-ing the design of the Domain Model, in which case we’ll still be fiddling around with a bunch of classes at a time. Domain Models are best tested using State-Based Testing; get the objects into a given state, call a method on one of them, assert the resulting state. The static events don’t impede that kind of testing at all.
</p>
<h4>What if we used Injection instead of Statics?</h4>
<p style="padding: 0em 1em;">
Also, you’ll find that each Service Layer class will need to subscribe to all the Domain Model’s events, something that is easily handled by a base class. I will state that I have tried doing this without a static class, and injecting that singleton object into the Service Layer classes, and in that setter having them subscribe to its events. This was also pulled into a base class. The main difference was that the Dependency Injection solution required injecting that object into Domain Objects as well. Personally, I’m against injection for domain objects. So all in all, the static solution comes with less overhead than that based on injection.
</p>
<h4>Summary</h4>
<p style="padding: 0em 1em;">
In summary, beyond the &#8220;technical basics&#8221; of being aware of your data volumes and designing your Domain Model to handle each use case performantly, I’ve found these techniques useful for designing its API as well as communicating my intent around persistence transparency. So give it a try. I’d be grateful to hear your thoughts on the matter as well as what else you’ve found that works.
</p>
<p><u style="padding: 0em 1em;">Related posts:</u></p>
<ul style="padding: 0em 1em;">
<li>
<a href="http://udidahan.weblogs.us/2007/04/23/fetching-strategy-design/">Fetching Strategy Design</a> &#8211; showing how to separate the concern of eager loading from both your Domain Model and your Service Layer.
</li>
<li>
<a href="http://udidahan.weblogs.us/2007/03/06/better-domain-driven-design-implementation/">Better Domain-Driven Design Implementation</a> &#8211; showing the basics of how valuable interfaces between your Domain Model and the Service Layer can be.
</li>
<li>
<a href="http://udidahan.weblogs.us/2007/04/15/lazy-loading-and-how-messaging-fixes-everything-again/">Lazy Loading, and how messaging fixes everything again</a> &#8211; describing the advantage of O/R mapping your message classes as well.
</li>
<li>
<a href="http://udidahan.weblogs.us/2007/03/28/query-objects-vs-methods-on-a-repository/">Query Objects vs Methods on a Repository</a> &#8211; discussing the scalability (in terms of number of developers and queries) of Query Objects.
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/06/04/performant-and-explicit-domain-models/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Multi-core CPU utilization with the Bus API</title>
		<link>http://www.udidahan.com/2007/05/11/multi-core-cpu-utilization-with-the-bus-api/</link>
		<comments>http://www.udidahan.com/2007/05/11/multi-core-cpu-utilization-with-the-bus-api/#comments</comments>
		<pubDate>Fri, 11 May 2007 22:59:43 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Architecture]]></category>
		<category><![CDATA[ESB]]></category>
		<category><![CDATA[Pub/Sub]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/05/11/multi-core-cpu-utilization-with-the-bus-api/</guid>
		<description><![CDATA[The issue of efficiently utilizing multi-core CPUs is gaining wider and wider mindshare. The debate on whether to use threads or processes is heating up. Savas is coming at it from the parallelism angle and I think that I&#8217;m with him on this.
When I base my designs around the Bus API, all my logic is [...]]]></description>
			<content:encoded><![CDATA[<p>The issue of efficiently utilizing multi-core CPUs is gaining wider and wider mindshare. The debate on whether to use <a href="http://bitworking.org/news/170/The-future-of">threads or processes</a> is heating up. Savas is coming at it from the <a href="http://savas.parastatidis.name/2007/05/02/4d59b3a4-1ef0-4dfb-9134-0f416113d689.aspx">parallelism angle</a> and I think that I&#8217;m with him on this.</p>
<p>When I base my designs around the <a href="http://udidahan.weblogs.us/2006/06/02/can-indigo-be-my-bus/">Bus API</a>, all my logic is both thread and process neutral. The implementation of the bus could be such that it uses <a href="http://udidahan.weblogs.us/2005/05/18/update-of-threadsafequeue-dont-multi-thread-without-it/">thread safe queues</a> for single process deployment. Named Pipes or even <a href="http://udidahan.weblogs.us/category/msmq/">MSMQ</a> could be used for multi-process communication. It&#8217;s all just an implementation detail.</p>
<p>It never ceases to amaze me the way these basic design principles show up fractally, at multiple levels of abstraction.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/05/11/multi-core-cpu-utilization-with-the-bus-api/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Starting and stopping threads</title>
		<link>http://www.udidahan.com/2007/05/02/starting-and-stopping-threads/</link>
		<comments>http://www.udidahan.com/2007/05/02/starting-and-stopping-threads/#comments</comments>
		<pubDate>Wed, 02 May 2007 06:58:37 +0000</pubDate>
		<dc:creator>thesoftwaresimplist</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://udidahan.weblogs.us/2007/05/02/starting-and-stopping-threads/</guid>
		<description><![CDATA[I ran into this question online and it&#8217;s something that comes up often with clients looking to do high-performance, safe, multi-threaded systems:

We have some programming module that runs for 8-10 hrs to accomplish the desire tasks. As this application is developed as Web application. So we have launch these programs with in thread context so [...]]]></description>
			<content:encoded><![CDATA[<p>I ran into this question online and it&#8217;s something that comes up often with clients looking to do high-performance, safe, multi-threaded systems:</p>
<blockquote><p>
We have some programming module that runs for 8-10 hrs to accomplish the desire tasks. As this application is developed as Web application. So we have launch these programs with in thread context so that it could run and finish the task even if the browser times out. </p>
<p>LongRunningProcess lrp = new LongRunningProcess();<br />
Thread t = new Thread();<br />
t.start(lrp.execute()); </p>
<p>But now we want to add this processes or thread into some storage so that we could monitor which task is running or failed. </p>
<p>What is the best way to monitor these thread preferably in a separate web form? It would be ideal if we could stop/cancel/restart each thread. </p>
<p>Hope to hear from you soon. </p>
<p>Regards
</p></blockquote>
<p>I want to just point out the main building block I use for such situations, a simple WorkerThread class. On top of it, many things can be built, my <a href="http://udidahan.weblogs.us/2007/04/22/basic-messaging-infrastructure/">Basic Messaging Infrastructure</a> for example.</p>
<p>So here&#8217;s the code, licensed under the <a href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 License</a>:</p>
<pre>
using System;
using System.Threading;
using log4net;

namespace UdiDahan.Threading
{
    public delegate void Callback();

    public class WorkerThread
    {
        private Callback methodToRunInLoop;
        private Thread thread;

        public WorkerThread(Callback methodToRunInLoop)
        {
            this.methodToRunInLoop = methodToRunInLoop;
            this.thread = new Thread(new ThreadStart(this.Loop));
            this.thread.SetApartmentState(ApartmentState.MTA);
            this.thread.Name = "Worker";
        }

        public void Start()
        {
            if (!this.thread.IsAlive)
                this.thread.Start();
        }

        public void Stop()
        {
            lock (_toLock)
                _stopRequested = true;
        }

        protected void Loop()
        {
            while (!StopRequested)
            {
                try
                {
                    this.methodToRunInLoop();
                }
                catch(Exception e)
                {
                    log.Error("Exception reached top level.", e);
                }
            }
        }

        protected bool StopRequested
        {
            get
            {
                bool result;
                lock (_toLock)
                    result = _stopRequested;

                return result;
            }
        }
        private bool _stopRequested;
        private object _toLock = new object();

        private static ILog log = LogManager.GetLogger(typeof(WorkerThread));
    }
}
</pre>
<p>Also, if you’re in the giving spirit and feel like donating something back, please <a href="/donate/">do so</a>. It will make it that much easier for me to continue supporting your use of this code.</p>
<p>Please send any questions or comments to <a href="mailto:threading@UdiDahan.com">Threading@UdiDahan.com</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.udidahan.com/2007/05/02/starting-and-stopping-threads/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
