<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-455072646448673416</id><updated>2012-01-24T16:53:38.530Z</updated><category term='Rx'/><category term='CLR'/><category term='WCF'/><category term='patterns'/><category term='Smart Client'/><category term='CAB'/><category term='Dialog'/><category term='UI'/><category term='Design'/><category term='Code Quality'/><category term='Chart'/><category term='Security'/><category term='WPF'/><category term='Event'/><category term='training'/><category term='Cloud'/><category term='Concurrency'/><category term='ASP.NET'/><title type='text'>LeeCampbell</title><subtitle type='html'>Concept to solution</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>77</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-4276047715918312166</id><published>2011-06-21T16:22:00.001+01:00</published><updated>2011-06-21T16:22:27.583+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><title type='text'>The definitive list of Rx sites</title><content type='html'>&lt;p&gt;Over at the &lt;a title="Rx forums" href="http://social.msdn.microsoft.com/Forums/en-US/rx" target="_blank"&gt;Rx forums&lt;/a&gt;, &lt;a title="Eamon Otuathail" href="http://social.msdn.microsoft.com/profile/eamon_otuathail/?type=forum" target="_blank"&gt;Eamon_OTuathail&lt;/a&gt; has created what seems to be &lt;a title="The list of Rx sites!" href="http://social.msdn.microsoft.com/Forums/en-US/rx/thread/2cbd3b1c-d535-46ba-a9cf-3cd576a8e7c2" target="_blank"&gt;the list of Rx sites&lt;/a&gt;. It is a list of Blogs and open source projects.&lt;/p&gt;  &lt;p&gt;Great stuff. This should save a lot of time for a lot of people.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://social.msdn.microsoft.com/Forums/en-US/rx/thread/2cbd3b1c-d535-46ba-a9cf-3cd576a8e7c2"&gt;http://social.msdn.microsoft.com/Forums/en-US/rx/thread/2cbd3b1c-d535-46ba-a9cf-3cd576a8e7c2&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Humbled to make the grade.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-4276047715918312166?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/4276047715918312166/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=4276047715918312166' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/4276047715918312166'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/4276047715918312166'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2011/06/definitive-list-of-rx-sites.html' title='The definitive list of Rx sites'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-5163644677581075238</id><published>2011-06-18T12:00:00.001+01:00</published><updated>2011-06-18T12:00:57.326+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='Code Quality'/><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><category scheme='http://www.blogger.com/atom/ns#' term='Design'/><category scheme='http://www.blogger.com/atom/ns#' term='CLR'/><title type='text'>Isolating custom Library dependencies versions from consumer dependency versions</title><content type='html'>&lt;p&gt;&lt;em&gt;This post is more about the CLR and dependency management than it is about Rx. However at this point in Rx’s lifecycle it seems relevant to comment on. The same principles could obviously be applied to open source projects et. al.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;I have recently heard of an interesting situation that no-doubt has proved troublesome to people before. This problem is particularly interesting with Rx and it’s recent rate of versions. If you are trying to incorporate Rx into a library of yours and you then want to publish that library, you are effectively forcing users to use the same version of Rx that you do. Considering that a version of Rx comes out say every two months and that often there are &lt;a title="Breaking changes to Rx v1.0.10425" href="http://leecampbell.blogspot.com/2011/06/rx-v1010425breaking-changes.html"&gt;breaking changes&lt;/a&gt;, this can create quite a mess. It is also made more interesting that up until recently they have not specified if a release was experimental or considered stable.&lt;/p&gt;  &lt;p&gt;To provide an example to better understand my particular point; imagine you have a library that wraps a messaging platform. You want to avoid the use of Events and APM, and expose things via IObservable&amp;lt;T&amp;gt;. You feel happy that IObservable&amp;lt;T&amp;gt; is exposed natively in .NET 4 so you should not have to expose your implementations of Rx. You do however, want to use Rx as it has features you need and don’t want to (re-)write yourself. Your standard approaches to package/deployment are:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;deploy the parts of the Rx libraries you use with your code. Users can just put them all into a “lib\MyFramework” folder and reference them.&lt;/li&gt;    &lt;li&gt;excluded the libraries from your code and set Specific Version = False and hope your code will work with the consumer’s version of Rx&lt;/li&gt;    &lt;li&gt;use a package management tool like Nuget to publish your package and specify the valid versions of Rx your library will work with.&lt;/li&gt;    &lt;li&gt;rely on things being in the GAC so you can utilise the side-by-side versioning it provides&lt;/li&gt;    &lt;li&gt;just try and implement the parts of Rx you want and avoid DLL Hell.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I gave this some thought and I think I have come up with a solution that could help library authors protect themselves. While there is the obvious option of using Nuget as part of your dependency management, this does not solve the problem, it just eases the pain. If the customer wants to use the latest version of Rx and you only support the 3 previous versions, your customer is still in some trouble.&lt;/p&gt;  &lt;p&gt;The theory i had was that I can specify the specific version of Rx I want to reference in my library, the problem being that it may be named the same as the client’s referenced version. Depending on where their references were built to, they could overwrite each other. It seemed the solution was to embed the dependency into my library. &lt;/p&gt;  &lt;p&gt;This turns out to actually be quite easy. If you have a project in visual studio that references your version of Rx, you have to follow these steps:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Ensure you have a file reference (not a project or a GAC reference) to the dependency, in this case System.Reactive.dll&lt;/li&gt;    &lt;li&gt;Set the reference to be Specific Version = True&lt;/li&gt;    &lt;li&gt;Set the reference Copy Local = False&lt;/li&gt;    &lt;li&gt;Embed the dependency into your library. I created a folder in my project called EmbeddedAssemblies. I “&lt;em&gt;Add Existing…&lt;/em&gt;” to this folder, navigate to the dependencies (just System.Reactive.dll in this case), and then choose “&lt;em&gt;Add as Link…&lt;/em&gt;”&lt;/li&gt;    &lt;li&gt;Set the “&lt;em&gt;Build Action&lt;/em&gt;” of&amp;#160; the newly added link to &lt;em&gt;Embedded Resource&lt;/em&gt;&lt;/li&gt;    &lt;li&gt;Ensure that the resource is loaded correctly at run time…&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The last part of that list proves to be not too hard. You can hook on to the &lt;a title="AppDomain.AssemblyResolve Event - MSDN" href="http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx"&gt;AppDomain.AssemblyResolve&lt;/a&gt; event and load your embedded resource. You can return your embedded dependency by reading the byte stream and creating the assembly from it and then returning that in the event handler&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;internal&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; DependencyResolver
{
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; _isSet = 0;

  &lt;span class="kwrd"&gt;internal&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Ensure()
  {
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (Interlocked.CompareExchange(&lt;span class="kwrd"&gt;ref&lt;/span&gt; _isSet, 1, 0) == 0)
    {
      var thisAssembly = Assembly.GetExecutingAssembly();
      var assemblyName = &lt;span class="kwrd"&gt;new&lt;/span&gt; AssemblyName(thisAssembly.FullName).Name;
      var embededAssemblyPrefix = assemblyName + &lt;span class="str"&gt;&amp;quot;.EmbeddedAssemblies.&amp;quot;&lt;/span&gt;;

      var myEmbeddedAssemblies =
        Assembly.GetExecutingAssembly().GetManifestResourceNames()
          .Where(name =&amp;gt; name.StartsWith(embededAssemblyPrefix))
          .Select(resourceName =&amp;gt;
                    {
                      &lt;span class="kwrd"&gt;using&lt;/span&gt; (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                      {
                        var assemblyData = &lt;span class="kwrd"&gt;new&lt;/span&gt; Byte[stream.Length];
                        stream.Read(assemblyData, 0, assemblyData.Length);
                        &lt;span class="kwrd"&gt;return&lt;/span&gt; Assembly.Load(assemblyData);
                      }
                    })
          .ToDictionary(ass =&amp;gt; ass.FullName);

      AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =&amp;gt;
                                                    {
                                                      Assembly assemblyToLoad = &lt;span class="kwrd"&gt;null&lt;/span&gt;;
                                                      myEmbeddedAssemblies.TryGetValue(args.Name, &lt;span class="kwrd"&gt;out&lt;/span&gt; assemblyToLoad);
                                                      &lt;span class="kwrd"&gt;return&lt;/span&gt; assemblyToLoad;
                                                    };
    }
  }
}&lt;/pre&gt;

&lt;p&gt;You can return null in the event handler to say I don't know how to load this assembly. This allows others to be able to have a go at loading the assembly in the same way.&lt;/p&gt;

&lt;p&gt;Next, to ensure that my embedded dependency resolver is called, I opted to make a call to it in the static constructor of the key types in my library. eg&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; SomeProvider
{
  &lt;span class="kwrd"&gt;static&lt;/span&gt; SomeProvider()
  {
    DependencyResolver.Ensure();
  }

  &lt;span class="rem"&gt;//other stuff goes here...&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;Have a look at the example code by downloading this &lt;a title="MultiVersionSpike1 - code.google.com" href="http://code.google.com/p/rx-samples/downloads/detail?name=MultiVersionSpike1.zip&amp;amp;can=2&amp;amp;q="&gt;zip file&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Caveats : This is a thought and the code and concepts are only demo quality. I have not used this in production quality code. I also have not verified that the license allows for this style of packaging.&lt;/p&gt;

&lt;p&gt;Further links:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;a title="Using different version of the same dll in one application" href="http://blogs.msdn.com/b/abhinaba/archive/2005/11/30/498278.aspx"&gt;Using different version of the same dll in one application&lt;/a&gt; – extern alias keyword&lt;/li&gt;

  &lt;li&gt;&lt;a title="Best Practice for Assembly Loading" href="http://msdn.microsoft.com/en-us/library/dd153782.aspx"&gt;Best Practice for Assembly Loading&lt;/a&gt; – MSDN&lt;/li&gt;

  &lt;li&gt;Questions around the &lt;a title="ETA for RTM version - Rx Forums" href="http://social.msdn.microsoft.com/Forums/en/rx/thread/95f16367-89df-4e89-bd8d-b4aef55ba969"&gt;stability&lt;/a&gt; and &lt;a title="golive and redist.txt - Rx Forums" href="http://social.msdn.microsoft.com/Forums/eu/rx/thread/e128d25c-c40f-4cb2-ae09-b4ade19cb98e"&gt;license&lt;/a&gt; for &lt;a title="Is the latest build a No-Go-Live Preview?" href="http://social.msdn.microsoft.com/Forums/en-US/rx/thread/77d01908-873b-4ef6-8ac3-adbd7aee424b"&gt;Rx releases&lt;/a&gt;&lt;/li&gt;

  &lt;li&gt;&lt;a title="Embed application’s depended dlls - Excerpt #2 from CLR via C#, Third Edition" href="http://blogs.msdn.com/b/microsoft_press/archive/2010/02/03/jeffrey-richter-excerpt-2-from-clr-via-c-third-edition.aspx"&gt;Embed application’s depended dlls&lt;/a&gt; – Jeffery Richter &lt;/li&gt;
&lt;/ul&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:8d000ad2-3908-42a9-a27b-021a0abccdf6" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-5163644677581075238?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/5163644677581075238/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=5163644677581075238' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5163644677581075238'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5163644677581075238'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2011/06/isolating-custom-library-dependencies.html' title='Isolating custom Library dependencies versions from consumer dependency versions'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-5962559873551641297</id><published>2011-06-05T23:42:00.000+01:00</published><updated>2011-06-05T23:42:00.126+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><title type='text'>Rx v.1.0.10425–Breaking changes!</title><content type='html'>&lt;p&gt;For those that follow Rx, many will have noticed a new drop was made available in late April 2011. This was interesting for numerous reasons:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;I believe that it was the first drop since the Rx team move off of the dev labs site and on to the Microsoft Data site &lt;/li&gt;    &lt;li&gt;They have supplied two downloads, Supported and Experimental &lt;/li&gt;    &lt;li&gt;It is available via Nuget &lt;/li&gt;    &lt;li&gt;It broke most of the sample code of this blog&lt;/li&gt;    &lt;li&gt;...It has massive breaking changes ! &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;The first thing I noticed was that only the more recent frameworks were in the “supported” release i.e. .NET 4, Silverlight 4 and Windows Phone. Next, when you open up the install directory (which has moved, again) the files are different to previous releases. &lt;/p&gt;  &lt;p&gt;This is a comparison of the location and files of the old v.s. new version (.NET 4 target):&lt;/p&gt;  &lt;pre class="csharpcode"&gt;C:\Program Files\Microsoft Cloud Programmability\Reactive Extensions\v1.0.2856.0\Net4
System.CoreEx.dll
System.Interactive.dll
System.Linq.Async.dll
System.Reactive.ClientProfile.dll
System.Reactive.dll
System.Reactive.ExtendedProfile.dll
System.Reactive.Testing.dll

C:\Program Files\Microsoft Reactive Extensions SDK\v1.0.10425\Binaries\.NETFramework\v4.0
Microsoft.Reactive.Testing.dll
System.Reactive.dll
System.Reactive.Providers.dll
System.Reactive.Windows.Forms.dll
System.Reactive.Windows.Threading.dll&lt;/pre&gt;

&lt;p&gt;Note the files names are named &lt;em&gt;System.Reactive&lt;/em&gt; instead of hijacking the existing BCL namespaces such as &lt;em&gt;System&lt;/em&gt;, &lt;em&gt;System.IO&lt;/em&gt;, &lt;em&gt;System.Linq&lt;/em&gt; etc. Here are a list of the old and new Namespaces found in the Rx libraries with the count of the Types in each namespace.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;C:\Program Files\Microsoft Cloud Programmability\Reactive Extensions\v1.0.2856.0\Net4
System                         6
System.Collections.Generic     21
System.Concurrency             14
System.Diagnostics             1
System.Disposables             8
System.IO                      1
System.Joins                   34
System.Linq                    13
System.Reactive.Testing        4
System.Reactive.Testing.Mocks  10
System.Threading.Tasks         1
System.Web                     1
System.Windows.Forms           1
System.Windows.Threading       1

C:\Program Files\Microsoft Reactive Extensions SDK\v1.0.10425\Binaries\.NETFramework\v4.0
Microsoft.Reactive.Testing     7
System                         1
System.Reactive                10
System.Reactive.Concurrency    16
System.Reactive.Disposables    9
System.Reactive.Joins          34
System.Reactive.Linq           8
System.Reactive.Subjects       8
System.Reactive.Threading.Tasks 1&lt;/pre&gt;

&lt;h4&gt;Summary of impact&lt;/h4&gt;

&lt;p&gt;Here is a quick list of the changes that have affected the code from the samples off this blog&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Unit &lt;/em&gt;has been moved to &lt;em&gt;System.Reactive&lt;/em&gt;. I imagine to prevent any conflicts with FSharp’s &lt;em&gt;Unit&lt;/em&gt;?&lt;/p&gt;

&lt;p&gt;&lt;em&gt;EventLoopScheduler&lt;/em&gt; no longer has a constructor that takes a string for the name of the thread, it instead takes a function to act as a Thread Factory so you can use that to specify a name for the thread instead.&lt;/p&gt;

&lt;p&gt;Similar methods have been collapsed to overloads. For example; &lt;em&gt;BufferWithTime&lt;/em&gt;, &lt;em&gt;BufferWithCount&lt;/em&gt; &amp;amp; &lt;em&gt;BufferTimeOrCount&lt;/em&gt; are all just &lt;em&gt;Buffer&lt;/em&gt; with various overloads. Same goes for &lt;em&gt;WindowWithTime&lt;/em&gt;, &lt;em&gt;WIndowWithCount&lt;/em&gt; &amp;amp; &lt;em&gt;WindowTimeOrCount&lt;/em&gt;. &lt;em&gt;GenerateWithTime&lt;/em&gt; is now just an overload of &lt;em&gt;Generate&lt;/em&gt;. &lt;em&gt;CreateWithDisposable&lt;/em&gt; is now just an overload of &lt;em&gt;Create&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Potentially confusing names have been adjusted. I must admit, I found &lt;em&gt;AsyncSubject&lt;/em&gt; and odd name, and also found it odd that &lt;em&gt;Prune&lt;/em&gt; was the method you would use to transform an existing observable to one that exhibited AsynchSubject behaviour. The new version of this is the far more appropriately named &lt;em&gt;TakeLast(int)&lt;/em&gt;. Obviously just pass a value of 1 to get the old semantics of &lt;em&gt;Prune&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;The&lt;em&gt; Run&lt;/em&gt; method has now been renamed the more obvious (well to new comers) &lt;em&gt;ForEach&lt;/em&gt;. It is a bit of an enumerable construct, but that is cool.&lt;/p&gt;

&lt;p&gt;My big problem has been the disappearance of the IsEmpty extension method. So I had a long think about this and have decided that you can replace it by creating your own extension method that looks like this&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ObservableExtensions
{
  &lt;span class="rem"&gt;//Is missing now the System.Interactive has been dropped&lt;/span&gt;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IObservable&amp;lt;&lt;span class="kwrd"&gt;bool&lt;/span&gt;&amp;gt; IsEmpty&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IObservable&amp;lt;T&amp;gt; source)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; source.Materialize()
        .Take(1)
        .Select(n =&amp;gt; n.Kind == NotificationKind.OnCompleted
                      || n.Kind == NotificationKind.OnError);
  }
}&lt;/pre&gt;

&lt;p&gt;For even more details, check out the &lt;a title="New release: Reactive Extensions 1.0.10425" href="http://social.msdn.microsoft.com/Forums/en-US/rx/thread/527002a3-18af-4eda-8e35-760ca0006b98"&gt;forum post&lt;/a&gt; that has the summary release notes and allsorts of rants about what has changed and what is causing problems for other (+ some helpful tips).&lt;/p&gt;

&lt;p&gt;&lt;a href="http://social.msdn.microsoft.com/Forums/en-US/rx/thread/527002a3-18af-4eda-8e35-760ca0006b98"&gt;http://social.msdn.microsoft.com/Forums/en-US/rx/thread/527002a3-18af-4eda-8e35-760ca0006b98&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This change is not one that you can just take and expect all to be well. However assuming that you can just update some references and add the missing extensions to you own library, you could be fine. &lt;/p&gt;

&lt;h4&gt;Changes to TestScheduler&lt;/h4&gt;

&lt;p&gt;The real problems come from the big changes to the testing part of Rx. This appears to have undergone a complete change and most of my existing code does not work. This looks like a big and possibly welcome change to the TestScheduler. &lt;/p&gt;

&lt;h5&gt;Problems with the previous TestScheduler&lt;/h5&gt;

&lt;p&gt;There were some fundamental problems with the TestScheduler as it was. There were problems with running it to a specific point in time if there were not any actions scheduled for that point in time. For example, the old TestScheduler would allow you to request that it run to say 5seconds. If there were no actions scheduled, then the clock would not actually advance. You could then Schedule an action to happen at 3Seconds (effectively in the past) and then call Run and it would execute the actions. Hmmm.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;TestScheduler scheduler = &lt;span class="kwrd"&gt;new&lt;/span&gt; TestScheduler();
scheduler.Schedule(()=&amp;gt;{Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Running at 1seconds&amp;quot;&lt;/span&gt;);}, TimeSpan.FromSeconds(1));
scheduler.RunTo( scheduler.FromTimeSpan(TimeSpan.FromSeconds(5)));
&lt;span class="rem"&gt;//The next line is scheduled in the past and somehow this all works!&lt;/span&gt;
scheduler.Schedule(()=&amp;gt;{Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Running at 3seconds&amp;quot;&lt;/span&gt;);}, TimeSpan.FromSeconds(3));
scheduler.Run();&lt;/pre&gt;

&lt;p&gt;There also seemed to be a lack of functionality for running to a relative point in time. I have used these extension methods to work around this shortcoming.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; TestSchedulerExtensions
{
  &lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// Runs the scheduler from now to the given TimeSpan. Advances relative to it's &amp;lt;c&amp;gt;Now&amp;lt;/c&amp;gt; value.&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; RunNext(&lt;span class="kwrd"&gt;this&lt;/span&gt; TestScheduler scheduler, TimeSpan interval)
  {
    var tickInterval = scheduler.FromTimeSpan(interval);
    scheduler.RunTo(scheduler.Ticks + tickInterval + 1);
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; RunTo(&lt;span class="kwrd"&gt;this&lt;/span&gt; TestScheduler scheduler, TimeSpan interval)
  {
    var tickInterval = scheduler.FromTimeSpan(interval);
    scheduler.RunTo(tickInterval);
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Step(&lt;span class="kwrd"&gt;this&lt;/span&gt; TestScheduler scheduler)
  {
    scheduler.RunTo(scheduler.Ticks + 1);
  }

  &lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// Provides a fluent interface so that you can write&amp;lt;c&amp;gt;7.Seconds()&amp;lt;/c&amp;gt; instead of &amp;lt;c&amp;gt;TimeSpan.FromSeconds(7)&amp;lt;/c&amp;gt;.&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;param name=&amp;quot;seconds&amp;quot;&amp;gt;A number of seconds&amp;lt;/param&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;returns&amp;gt;Returns a System.TimeSpan to represents the specified number of seconds.&amp;lt;/returns&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; TimeSpan Seconds(&lt;span class="kwrd"&gt;this&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; seconds)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; TimeSpan.FromSeconds(seconds);
  }
}&lt;/pre&gt;

&lt;p&gt;However on initial inspection of the new TestScheduler there appears to be features that support running to an absolute or relative time. It looks like that the Post on testing Rx will need a re-write &lt;img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-sadsmile" alt="Sad smile" src="http://lh6.ggpht.com/-JrY-6FA8uYU/TewFtPT5TLI/AAAAAAAACrE/p_zjKJE1Poc/wlEmoticon-sadsmile%25255B2%25255D.png?imgmax=800" /&gt;&lt;/p&gt;

&lt;p&gt;
  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:5dda8b86-494b-451a-9dba-f42b361470c2" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;&lt;/div&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-5962559873551641297?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/5962559873551641297/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=5962559873551641297' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5962559873551641297'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5962559873551641297'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2011/06/rx-v1010425breaking-changes.html' title='Rx v.1.0.10425–Breaking changes!'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh6.ggpht.com/-JrY-6FA8uYU/TewFtPT5TLI/AAAAAAAACrE/p_zjKJE1Poc/s72-c/wlEmoticon-sadsmile%25255B2%25255D.png?imgmax=800' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-898853230925169045</id><published>2011-05-29T00:00:00.000+01:00</published><updated>2011-05-29T00:00:01.101+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><title type='text'>Rxx - Extension to the Reactive Extensions…</title><content type='html'>&lt;p&gt;For those of you that use the Rx forums you will have no doubt found an answer or even had your question answered by either James Miles or Dave Sexton. These two have put their mighty brains together to produce some handy extensions to Rx. They went with the fairly obvious (but tongue-in-cheek) name Rxx.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://social.msdn.microsoft.com/Forums/hu-HU/rx/thread/32f6ee34-5edf-4038-894c-ab47fc893a78"&gt;http://social.msdn.microsoft.com/Forums/hu-HU/rx/thread/32f6ee34-5edf-4038-894c-ab47fc893a78&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The key features that anyone that has been using Rx for a while will immediately be interested in are the&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Tracing/Logging&lt;/li&gt;    &lt;li&gt;PropertyChanged and PropertyDescriptor extensions&lt;/li&gt;    &lt;li&gt;FileSystemWatcher&lt;/li&gt;    &lt;li&gt;and the uber-funky OperationalObservable eg. var os = xs + ys – zs;&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;For a more complete list look at the &lt;a title="Rxx - documentation" href="http://rxx.codeplex.com/documentation"&gt;documentation&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;This could well be a community contribution that could help guide the actual Rx implementations that start coming out of Microsoft (like the Community Extensions around for P&amp;amp;P propjects). James and Dave seem to be taking this quite seriously. They have been checking regularly (with sensible comments!), constructed the codeplex site very well and have already got their issue trackers running.&lt;/p&gt;  &lt;p&gt;This is one to keep an eye on.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://rxx.codeplex.com/"&gt;http://rxx.codeplex.com/&lt;/a&gt;&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:9aab118f-c31a-4226-a09f-8687cbfaea8e" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-898853230925169045?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/898853230925169045/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=898853230925169045' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/898853230925169045'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/898853230925169045'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2011/05/rxx-extension-to-reactive-extensions.html' title='Rxx - Extension to the Reactive Extensions…'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-8814338294777683709</id><published>2011-05-25T23:50:00.001+01:00</published><updated>2011-05-26T00:17:18.271+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='Concurrency'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Rx code from Perth Presentation</title><content type='html'>&lt;p&gt;Sorry about the delay in getting this code up. For those who could not make it, my part of the presentation did a bit of an intro and then discussed the testability of Rx and the easy way to deal with streaming data such as pricing in a financial industry.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh6.ggpht.com/-S30XM8u2PEE/Td2N8O8Y4OI/AAAAAAAACq0/BL7TsYF078M/s1600-h/RxSamplesGalleryScreenShot%25255B16%25255D.png"&gt;&lt;img style="display: block; float: none; margin-left: auto; margin-right: auto" title="RxSamplesGalleryScreenShot" alt="RxSamplesGalleryScreenShot" src="http://lh4.ggpht.com/-qpTR7Xq1uH0/Td2N9HTOdCI/AAAAAAAACq4/lmFwLex2Oqw/RxSamplesGalleryScreenShot_thumb%25255B14%25255D.png?imgmax=800" width="630" height="470" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://lh6.ggpht.com/-ejxU40Q0asQ/Td2N-aEH_UI/AAAAAAAACq8/PkgbGDS6MaI/s1600-h/RxSamplesTWAPChartScreenShot%25255B3%25255D.png"&gt;&lt;img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: block; float: none; margin-left: auto; border-top: 0px; margin-right: auto; border-right: 0px; padding-top: 0px" title="RxSamplesTWAPChartScreenShot" border="0" alt="RxSamplesTWAPChartScreenShot" src="http://lh5.ggpht.com/-FLwoZbXHMQk/Td2N_di6f4I/AAAAAAAACrA/rCsYM01Cr6g/RxSamplesTWAPChartScreenShot_thumb%25255B1%25255D.png?imgmax=800" width="634" height="474" /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;The key samples from my half of the presentation that raised some interest was the testability of the Photo Gallery View model. The Gallery ViewModel was effectively this&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
&lt;span class="rem"&gt;/// Tested Rx implementation of the ViewModel&lt;/span&gt;
&lt;span class="rem"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;sealed&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; RxPhotoGalleryViewModel : INotifyPropertyChanged
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; RxPhotoGalleryViewModel(IImageService imageService, ISchedulerProvider scheduler)
    {
        IsLoading = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
        var files = imageService.EnumerateImages()
                                .ToObservable();

        files
            .SubscribeOn(scheduler.ThreadPool)
            .ObserveOn(scheduler.Dispatcher)
            .Subscribe(
                imagePath =&amp;gt;
                {
                    Images.Add(imagePath);
                },
                () =&amp;gt;
                {
                    IsLoading = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
                });
    }

    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; ObservableCollection&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; _images = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObservableCollection&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
    &lt;span class="kwrd"&gt;public&lt;/span&gt; ObservableCollection&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Images
    {
        get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _images; }
    }

    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; _isLoading;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsLoading
    {
        get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _isLoading; }
        set
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (_isLoading != &lt;span class="kwrd"&gt;value&lt;/span&gt;)
            {
                _isLoading = &lt;span class="kwrd"&gt;value&lt;/span&gt;;
                InvokePropertyChanged(&lt;span class="str"&gt;&amp;quot;IsLoading&amp;quot;&lt;/span&gt;);
            }
        }
    }

    &lt;span class="preproc"&gt;#region&lt;/span&gt; Implementation of INotifyPropertyChanged

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;event&lt;/span&gt; PropertyChangedEventHandler PropertyChanged;

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; InvokePropertyChanged(&lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (handler != &lt;span class="kwrd"&gt;null&lt;/span&gt;) handler(&lt;span class="kwrd"&gt;this&lt;/span&gt;, &lt;span class="kwrd"&gt;new&lt;/span&gt; PropertyChangedEventArgs(propertyName));
    }

    &lt;span class="preproc"&gt;#endregion&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;Except from the constructor, there is really just two properties that expose change notification for the WPF binding engine. Now the code in the constructor is demo-quality in the sense that it is not good practice to do so much work in the constructor. Maybe this would be better&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;sealed&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; RxPhotoGalleryViewModel
{
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; IImageService _imageService;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; ISchedulerProvider _scheduler;

    &lt;span class="kwrd"&gt;public&lt;/span&gt; RxPhotoGalleryViewModel(IImageService imageService, ISchedulerProvider scheduler)
    {
        _imageService = imageService;
        _scheduler = scheduler;
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Start()
    {
        IsLoading = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
        var files = _imageService.EnumerateImages()
                                .ToObservable();

        files
            .SubscribeOn(_scheduler.ThreadPool)
            .ObserveOn(_scheduler.Dispatcher)
            .Subscribe(
                imagePath =&amp;gt; Images.Add(imagePath),
                () =&amp;gt;IsLoading = &lt;span class="kwrd"&gt;false&lt;/span&gt;);
    }
&lt;span class="rem"&gt;//....&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;The test fixture is fairly simple. We pass in a mock implementation of the IImageService and the TestSchedulerProvider similar to the one shown in &lt;a title="Rx Part 8 – Testing Rx" href="http://leecampbell.blogspot.com/2010/10/rx-part-8-testing-rx.html"&gt;Rx Part 8 – Testing Rx&lt;/a&gt;. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;[TestClass]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; RxPhotoGalleryViewModelTests
{
    &lt;span class="kwrd"&gt;private&lt;/span&gt; Mock&amp;lt;IImageService&amp;gt; _imageSrvMock;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; TestSchedulderProvider _testSchedulderProvider;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; _expectedImages;

    [TestInitialize]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetUp()
    {
        _imageSrvMock = &lt;span class="kwrd"&gt;new&lt;/span&gt; Mock&amp;lt;IImageService&amp;gt;();
        _testSchedulderProvider = &lt;span class="kwrd"&gt;new&lt;/span&gt; TestSchedulderProvider();

        _expectedImages = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; { &lt;span class="str"&gt;&amp;quot;one.jpg&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;two.jpg&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;three.jpg&amp;quot;&lt;/span&gt; };
        _imageSrvMock.Setup(svc =&amp;gt; svc.EnumerateImages())
                        .Returns(_expectedImages);

    }

    [TestMethod]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Should_add_ImagesServiceResults_to_Images()
    {
        &lt;span class="rem"&gt;//Arrange&lt;/span&gt;
        &lt;span class="rem"&gt;// done in setup&lt;/span&gt;

        &lt;span class="rem"&gt;//Act&lt;/span&gt;
        var sut = &lt;span class="kwrd"&gt;new&lt;/span&gt; RxPhotoGalleryViewModel(_imageSrvMock.Object, _testSchedulderProvider);
        _testSchedulderProvider.ThreadPool.Run();
        _testSchedulderProvider.Dispatcher.Run();

        &lt;span class="rem"&gt;//Assert&lt;/span&gt;
        CollectionAssert.AreEqual(_expectedImages, sut.Images);
    }

    [TestMethod]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Should_set_IsLoading_to_true()
    {
        &lt;span class="rem"&gt;//Arrange&lt;/span&gt;
        &lt;span class="rem"&gt;// done in setup&lt;/span&gt;

        &lt;span class="rem"&gt;//Act&lt;/span&gt;
        var sut = &lt;span class="kwrd"&gt;new&lt;/span&gt; RxPhotoGalleryViewModel(_imageSrvMock.Object, _testSchedulderProvider);
            
        &lt;span class="rem"&gt;//--NOTE-- note the missing TestScheduler.Run() calls. This will stop any observable being processed. Cool.&lt;/span&gt;

        &lt;span class="rem"&gt;//Assert&lt;/span&gt;
        Assert.IsTrue(sut.IsLoading);
    }

    [TestMethod]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Should_set_IsLoading_to_false_when_completed_loading()
    {
        &lt;span class="rem"&gt;//Arrange&lt;/span&gt;
        &lt;span class="rem"&gt;// done in setup&lt;/span&gt;

        &lt;span class="rem"&gt;//Act&lt;/span&gt;
        var sut = &lt;span class="kwrd"&gt;new&lt;/span&gt; RxPhotoGalleryViewModel(_imageSrvMock.Object, _testSchedulderProvider);
        _testSchedulderProvider.ThreadPool.Run();
        _testSchedulderProvider.Dispatcher.Run();

        &lt;span class="rem"&gt;//Assert&lt;/span&gt;
        Assert.IsFalse(sut.IsLoading);
    }
}&lt;/pre&gt;

&lt;p&gt;As we now control the scheduling/concurrency we don't have to try to do anything fancy with Dispatchers,&amp;#160; BackgroundWorkers, ThreadPools or Tasks which are very difficult to perform unit testing on. Check out the pain that I went through to test responsive WPF apps in this post on &lt;a title="Responsive WPF UI - Part 5 -Testing multithreaded WPF code" href="http://leecampbell.blogspot.com/2009/02/responsive-wpf-user-interfaces-part-5.html"&gt;Testing Responsive WPF&lt;/a&gt; complete with DispatcherFrame and Thread.Sleep(300) in my tests &lt;img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-sadsmile" alt="Sad smile" src="http://lh6.ggpht.com/-LyqxW8W3rPI/Td2HmqV-evI/AAAAAAAACp4/nFswdCBb44I/wlEmoticon-sadsmile%25255B2%25255D.png?imgmax=800" /&gt;&lt;/p&gt;

&lt;p&gt;If you want the running code you can either pull the code down via SVN by following this &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or you can &lt;a title="rx-samples_PerthDemo.zip" href="http://code.google.com/p/rx-samples/downloads/detail?name=rx-samples_PerthDemo.zip&amp;amp;can=2&amp;amp;q="&gt;download the zip&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The PowerPoint presentation is &lt;a title="IntroductionToRx.pptx" href="http://code.google.com/p/rx-samples/downloads/detail?name=Introduction%20to%20Rx.pptx&amp;amp;can=2&amp;amp;q="&gt;here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You may also be interested in the &lt;a title="Rx Design Guidelines" href="http://blogs.msdn.com/b/rxteam/archive/2010/10/28/rx-design-guidelines.aspx"&gt;Design Guidelines&lt;/a&gt; produced by the Rx team at Microsoft and also where to get the &lt;a title="Get Started Developing with the Reactive Extensions" href="http://msdn.microsoft.com/en-us/data/gg577610"&gt;latest version of Rx&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Back to the &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;contents&lt;/a&gt; page for &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions for .NET Introduction&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;
  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:1932855f-fcc3-4d7b-8802-7b6fc6e41242" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-8814338294777683709?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/8814338294777683709/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=8814338294777683709' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/8814338294777683709'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/8814338294777683709'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2011/05/rx-code-from-perth-presentation.html' title='Rx code from Perth Presentation'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh4.ggpht.com/-qpTR7Xq1uH0/Td2N9HTOdCI/AAAAAAAACq4/lmFwLex2Oqw/s72-c/RxSamplesGalleryScreenShot_thumb%25255B14%25255D.png?imgmax=800' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-7104937367653414320</id><published>2011-05-11T05:48:00.003+01:00</published><updated>2011-05-11T05:54:52.246+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='Event'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Rx session in Perth, Australia</title><content type='html'>&lt;p&gt;James Miles and I will be giving a presentation on Rx to a Perth audience this Thursday. If you are in town then come on down!&lt;/p&gt;

&lt;p&gt;As those that read this blog will know, Rx is my thing at the moment so feel free to bring plenty of questions.&lt;/p&gt;

&lt;p&gt;Full details can be found at the &lt;a href="http://perthdotnet.org/"&gt;Perth .NET Community of Practice&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://perthdotnet.org/blogs/events/archive/2011/05/07/introduction-to-the-net-reactive-extensions-rx-with-lee-campbell-and-james-miles.aspx"&gt;Introduction to Rx with Lee Campbell and James Miles&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;See you there.&lt;br/&gt;
Lee&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-7104937367653414320?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/7104937367653414320/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=7104937367653414320' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7104937367653414320'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7104937367653414320'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2011/05/rx-session-in-perth-australia.html' title='Rx session in Perth, Australia'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-5316270593235637413</id><published>2011-03-14T07:25:00.001Z</published><updated>2011-03-14T08:00:11.480Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Rx Part 9–Join, Window, Buffer and Group Join</title><content type='html'>&lt;p&gt;While this series of posts is labelled as an introduction, this post takes us past the &lt;a title="Microsoft&amp;#39;s Standard Level Definitions (100 to 400)" href="http://blogs.technet.com/b/ieitpro/archive/2006/09/29/459944.aspx" target="_blank"&gt;100 level&lt;/a&gt; style posts. This post looks to tackle the interesting way of combing multiple streams of data. We have looked at versions of combining streams in earlier posts with SelectMany, Merge, Zip, Concat etc. The operators that we look at in this post are different for several reasons&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;They are new as of 2011 &lt;/li&gt;    &lt;li&gt;Their matching is based on events coinciding with each other based on some given window of time &lt;/li&gt;    &lt;li&gt;They offer some pretty powerful stuff that would otherwise be complex to code and just nasty if you went &lt;em&gt;sans-Rx&lt;/em&gt;. &lt;/li&gt; &lt;/ol&gt;  &lt;h4&gt;Buffer&lt;/h4&gt;  &lt;p&gt;Buffer is not a new operator to us, however it can now be conceptually grouped with the group-join operators. These operators all do something with a stream and a window of time. Each operator will open a window when the source stream produces a value. The way the window is closed and which values are exposed is the main difference between each of the operators. Let us first go back to our old friend BufferWithCount that we saw in the &lt;a title="Rx part 2 – Static and Extension methods" href="http://leecampbell.blogspot.com/2010/05/rx-part-2-static-and-extension-methods.html" target="_blank"&gt;second post&lt;/a&gt; in &lt;a title="Reactive Extensions for .NET an Introduction - LeeCampbell" href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html" target="_blank"&gt;this series&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;BufferWithCount will create a window when the first value is produced. It will then put that value in to an internal cache. The window will stay open until the count of values has been reached. Each of these values will have been cached. Now that the count has been reached the window will close and the cache will be OnNext’ed as an IList&amp;lt;T&amp;gt;. When the next value is produced from the source, the cache is cleared and we start again. This means that BufferWithCount will take an IObservable&amp;lt;T&amp;gt; and return an IObservable&amp;lt;IList&amp;lt;T&amp;gt;&amp;gt;. &lt;/p&gt;  &lt;p&gt;&lt;em&gt;Example Buffer with count of 3&lt;/em&gt;&lt;/p&gt;  &lt;pre class="csharpcode"&gt;source|-0-1-2-3-4-5-6-7-8-9|
result|-----0-----3-----6-9|
            1     4     7
            2     5     8 &lt;/pre&gt;

&lt;p&gt;&lt;em&gt;In this marble diagram, I have represented the list of values being returned at a point in time as a column of data. i.e. the values 0, 1 &amp;amp; 2 are all returned in the first buffer.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Understanding this it is not much of a leap to understand BufferWithTime. Instead of passing a count we pass a TimeSpan. The closing of the window (and therefore the buffer’s cache) is now dictated by time instead of the count of values produced. This is ever-so more complicated as we now have introduced some sort of scheduling. To produce the IList&amp;lt;T&amp;gt; at the correct point in time we need a scheduler assigned to performing the timing. This also makes testing this stuff a lot easier.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Example Buffer with time of 5 units&lt;/em&gt; 

  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;source|-0-1-2-3-4-5-6-7-8-9-|
result|----0----2----5----7-|
           1    3    6    8
                4         9&lt;/pre&gt;

&lt;h4&gt;Window&lt;/h4&gt;

&lt;p&gt;The Window operators are very similar to the Buffer operators, they only really differ by their return type. Where Buffer would take an IObservable&amp;lt;T&amp;gt; and return an IObservable&amp;lt;IList&amp;lt;T&amp;gt;&amp;gt;, the Window operators return an IObservable&amp;lt;IObservable&amp;lt;T&amp;gt;&amp;gt;. It is also worth noting that the Buffer operators will not yield their buffers until the window closes.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Example of Window with a count of 3&lt;/em&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;source |-0-1-2-3-4-5-6-7-8-9|
window0|-0-1-2|
window1        3-4-5|
window2              6-7-8|
window3                    9|&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Example of Window with time of 5 units&lt;/em&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;source |-0-1-2-3-4-5-6-7-8-9|
window0|-0-1-|
window1      2-3-4|
window2           -5-6-|
window3                7-8-9|&lt;/pre&gt;

&lt;p&gt;So the obvious difference here is that with the Window operators you get hold of the values from the source as soon as they are produced, but the Buffer operators you must wait until the window closes before the values are accessible.&lt;/p&gt;

&lt;h4&gt;Switch is the Anti Window &lt;img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://lh4.ggpht.com/_aee9WmSAaWE/TX3C2bp92oI/AAAAAAAACpU/IvhFjhbZZd4/wlEmoticon-smile%5B2%5D.png?imgmax=800" /&gt;&lt;/h4&gt;

&lt;p&gt;I think it is worth noting, at least from an academic point, that the Window operators produce IObservable&amp;lt;IObservable&amp;lt;T&amp;gt;&amp;gt; and that the Switch operator takes an IObservable&amp;lt;IObservable&amp;lt;T&amp;gt;&amp;gt; and returns an IObservable&amp;lt;T&amp;gt;. As the Window operators ensure that the windows (child streams) do not overlap, we can use the Switch operator to turn a windowed stream back into its original stream.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;//is the same as Observable.Interval(TimeSpan.FromMilliseconds(200)).Take(10)&lt;/span&gt;
var switchedWindow = Observable.Interval(TimeSpan.FromMilliseconds(200)).Take(10)
    .WindowWithTime(TimeSpan.FromMilliseconds(500))
    .Switch();&lt;/pre&gt;

&lt;h4&gt;Join&lt;/h4&gt;

&lt;p&gt;Join is not a new Method to the Rx library, but overload we are interested today in is new. From what I can see on the 2 original overloads that take an Array or an IEnumerable of Plan&amp;lt;T&amp;gt;, the usage can be replicated with Merge and Select. They are a bit of a mystery to me.&lt;/p&gt;

&lt;p&gt;The overload we are interested in is &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IObservable&amp;lt;TResult&amp;gt; Join&amp;lt;TLeft, TRight, TLeftDuration, TRightDuration, TResult&amp;gt;
(
    &lt;span class="kwrd"&gt;this&lt;/span&gt; IObservable&amp;lt;TLeft&amp;gt; left, 
    IObservable&amp;lt;TRight&amp;gt; right, 
    Func&amp;lt;TLeft, IObservable&amp;lt;TLeftDuration&amp;gt;&amp;gt; leftDurationSelector, 
    Func&amp;lt;TRight, IObservable&amp;lt;TRightDuration&amp;gt;&amp;gt; rightDurationSelector, 
    Func&amp;lt;TLeft, TRight, TResult&amp;gt; resultSelector
)&lt;/pre&gt;

&lt;p&gt;Now this is a fairly hairy signature to try and understand in one go, so let’s take it one parameter at a time.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;IObservable&amp;lt;TLeft&amp;gt; left&lt;/strong&gt; is source stream that defines when a window starts. This is just like the Buffer and Window operators, except that every value published from this source opens a new window. In Buffer and Window, some values just fell into an existing window.&lt;/p&gt;

&lt;p&gt;I like to think &lt;strong&gt;IObservable&amp;lt;TRight&amp;gt; right&lt;/strong&gt; as the window value stream. While the left stream controls opening the windows, the right stream will try to pair up with a value from the left stream.&lt;/p&gt;

&lt;p&gt;Let us imagine that our left stream produces a value, which creates a new window. If the right stream produces a value while the window is open then the &lt;strong&gt;resultSelector&lt;/strong&gt; function is called with the two values. This is the crux of join, pairing two values from a stream that occur with in the same window. This then leads us to our next question; When does the window close? The answer to this question is both the power and complexity of the Join operator. &lt;/p&gt;

&lt;p&gt;When &lt;strong&gt;left&lt;/strong&gt; produces a value, a window is opened. That value is also then passed to the &lt;strong&gt;leftDurationSelector&lt;/strong&gt; function. The result of this function is an IObservable&amp;lt;TLeftDuration&amp;gt;. When that IObservable OnNext’s &lt;em&gt;or&lt;/em&gt; Completes then the window for that value is closed. Note that it is irrelevant what the type of &lt;strong&gt;TLeftDuration&lt;/strong&gt; is. This initially left me with the feeling that IObservable&amp;lt;TLeftDuration&amp;gt; was all a bit over kill as you effectively just need some sort of event to say “Closed!”. However by allowing you to use IObservable you can do some clever stuff as we will see later.&lt;/p&gt;

&lt;p&gt;So let us first imagine a scenario where we have the left stream producing values twice as fast as the right stream. Imagine that we also never close the windows. We could do this by always returning Observable.Never&amp;lt;Unit&amp;gt;() from the &lt;strong&gt;leftDurationSelector&lt;/strong&gt; function. This would result in the following pairs being produced.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;left  |-0-1-2-3-4-5|
right |---A---B---C|

result|---0---0---0
          A   B   C

          1   1   1
          A   B   C

              2   2
              B   C

              3   3
              B   C

                  4
                  C

                  5
                  C&lt;/pre&gt;

&lt;p&gt;As you can see the left values are cached and replayed each time the right produces a value. &lt;/p&gt;

&lt;p&gt;Now it seems fairly obvious that if I immediately closed the window by returning Observable.Empty&amp;lt;Unit&amp;gt; or perhaps Observable.Return(0) that windows would never be opened so no pairs would ever get produced. However what could I do to make sure that these windows did not overlap so that once a second value was produced I would no longer see the first value? Well, if we returned the &lt;strong&gt;left&lt;/strong&gt; stream from the &lt;strong&gt;leftDurationSelector&lt;/strong&gt; that could do it. But wait, when we return the &lt;strong&gt;left&lt;/strong&gt; from the &lt;strong&gt;leftDurationSelector&lt;/strong&gt; it would try to create another subscription and that may introduce side effects. The quick answer to that is to Publish and RefCount the &lt;strong&gt;left&lt;/strong&gt; stream. If we do that the results look more like this.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;left  |-0-1-2-3-4-5|
right |---A---B---C|
result|---1---3---5
          A   B   C&lt;/pre&gt;

&lt;p&gt;This made me think that I could use Join to produce my own version of CombineLatest that we saw in the &lt;a title="RX Part 5 – Combining multiple IObservable streams" href="http://leecampbell.blogspot.com/2010/06/rx-part-5-combining-multiple.html" target="_blank"&gt;5th post in the series&lt;/a&gt;. If I had the values from left expire when the next value from left was OnNext’ed then I would be well on my way. However I need the same thing to happen for the right. Luckily the Join operator also provides us with a &lt;strong&gt;rightDurationSelector&lt;/strong&gt; that works just like the &lt;strong&gt;leftDurationSelector&lt;/strong&gt;. This is simple to implement, all I need to do is return a reference to the same left stream when a left value is produced and then the same for the right. The code looks like this.&lt;/p&gt;



&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IObservable&amp;lt;TResult&amp;gt; MyCombineLatest&amp;lt;TLeft, TRight, TResult&amp;gt;
(
    IObservable&amp;lt;TLeft&amp;gt; left, 
    IObservable&amp;lt;TRight&amp;gt; right, 
    Func&amp;lt;TLeft, TRight, TResult&amp;gt; resultSelector)
{
    var refcountedLeft = left.Publish().RefCount();
    var refcountedRight = right.Publish().RefCount();
    &lt;span class="kwrd"&gt;return&lt;/span&gt; Observable.Join(
            refcountedLeft,
            refcountedRight,
            &lt;span class="kwrd"&gt;value&lt;/span&gt; =&amp;gt; refcountedLeft,
            &lt;span class="kwrd"&gt;value&lt;/span&gt; =&amp;gt; refcountedRight,
            resultSelector);
}&lt;/pre&gt;



&lt;p&gt;While the code above is not production quality (it would need to have some gates in place to mitigate race conditions), it shows us the power that we could get with Join; we can actually use it to create other operators!&lt;/p&gt;

&lt;h4&gt;GroupJoin&lt;/h4&gt;

&lt;p&gt;When the Join operator pairs up values that coincide within a window, it would always produce just the left value and the right value to the &lt;strong&gt;resultSelector&lt;/strong&gt;. The &lt;strong&gt;GroupJoin&lt;/strong&gt; operator takes this one step further by passing the left value immediately to the &lt;strong&gt;resultSelector&lt;/strong&gt; with an IObservable of the right values that occur within the window. It’s signature is very similar to Join but note the difference in the &lt;strong&gt;resultSelector&lt;/strong&gt; Func.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IObservable&amp;lt;TResult&amp;gt; GroupJoin&amp;lt;TLeft, TRight, TLeftDuration, TRightDuration, TResult&amp;gt;
(
    &lt;span class="kwrd"&gt;this&lt;/span&gt; IObservable&amp;lt;TLeft&amp;gt; left, 
    IObservable&amp;lt;TRight&amp;gt; right, 
    Func&amp;lt;TLeft, IObservable&amp;lt;TLeftDuration&amp;gt;&amp;gt; leftDurationSelector, 
    Func&amp;lt;TRight, IObservable&amp;lt;TRightDuration&amp;gt;&amp;gt; rightDurationSelector, 
    Func&amp;lt;TLeft, IObservable&amp;lt;TRight&amp;gt;, TResult&amp;gt; resultSelector
)&lt;/pre&gt;

&lt;p&gt;If we went back to our first Join example where we had &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the &lt;strong&gt;left&lt;/strong&gt; producing values twice as fast as the right, &lt;/li&gt;

  &lt;li&gt;the left never expiring &lt;/li&gt;

  &lt;li&gt;the right immediately expiring &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;this is what the result may look like&lt;/p&gt;

&lt;pre class="csharpcode"&gt;left              |-0-1-2-3-4-5|
right             |---A---B---C|

0th window values   --A---B---C|
1st window values     A---B---C|
2nd window values       --B---C|
3rd window values         B---C|
4th window values           --C|
5th window values             C|&lt;/pre&gt;

&lt;p&gt;Now we could switch it around and have it that the left expired immediately and the right never expired the result may look like this&lt;/p&gt;

&lt;pre class="csharpcode"&gt;left              |-0-1-2-3-4-5|
right             |---A---B---C|

0th window values   |
1st window values     A|
2nd window values       A|
3rd window values         AB|
4th window values           AB|
5th window values             ABC|&lt;/pre&gt;

&lt;p&gt;This starts to make things interesting. Sharp readers may have noticed that with GroupJoin you could effectively re-create your own Join by doing something like this&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; IObservable&amp;lt;TResult&amp;gt; MyJoin&amp;lt;TLeft, TRight, TLeftDuration, TRightDuration, TResult&amp;gt;(
    IObservable&amp;lt;TLeft&amp;gt; left,
    IObservable&amp;lt;TRight&amp;gt; right,
    Func&amp;lt;TLeft, IObservable&amp;lt;TLeftDuration&amp;gt;&amp;gt; leftDurationSelector,
    Func&amp;lt;TRight, IObservable&amp;lt;TRightDuration&amp;gt;&amp;gt; rightDurationSelector,
    Func&amp;lt;TLeft, TRight, TResult&amp;gt; resultSelector)
{
    &lt;span class="kwrd"&gt;return&lt;/span&gt; Observable.GroupJoin
        (
            left, 
            right,
            leftDurationSelector,
            rightDurationSelector,
            (leftValue, rightValues)=&amp;gt;rightValues.Select(rightValue=&amp;gt;resultSelector(leftValue, rightValue))
        )
        .Merge();
}&lt;/pre&gt;

&lt;p&gt;I even was able to knock up my own version of WindowWithTime with this code below&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; IObservable&amp;lt;IObservable&amp;lt;T&amp;gt;&amp;gt; MyWindowWithTime&amp;lt;T&amp;gt;(IObservable&amp;lt;T&amp;gt; source, TimeSpan windowPeriod)
{
    &lt;span class="kwrd"&gt;return&lt;/span&gt; Observable.CreateWithDisposable&amp;lt;IObservable&amp;lt;T&amp;gt;&amp;gt;(o =&amp;gt;
        {
            var windower = &lt;span class="kwrd"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="kwrd"&gt;long&lt;/span&gt;&amp;gt;();
            var intervals = Observable.Concat(
                    Observable.Return(0l),
                    Observable.Interval(windowPeriod)
                )
                .Publish()
                .RefCount();

            var subscription = Observable.GroupJoin
                (
                    windower,
                    source.Do(_ =&amp;gt; { }, windower.OnCompleted),
                    _ =&amp;gt; windower,
                    _ =&amp;gt; Observable.Empty&amp;lt;Unit&amp;gt;(),
                    (left, sourceValues) =&amp;gt; sourceValues
                )
                .Subscribe(o);
            var intervalSubscription = intervals.Subscribe(windower);
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; CompositeDisposable(subscription, intervalSubscription);
        });
}&lt;/pre&gt;
Yeah it is not so pretty, but it is an academic exercise to show case GroupJoin. Those that have read Bart DeSmet’s &lt;a title="The essence of Linq - MiniLinq" href="http://blogs.bartdesmet.net/blogs/bart/archive/2010/01/01/the-essence-of-linq-minlinq.aspx" target="_blank"&gt;excellent MiniLinq post&lt;/a&gt; (and &lt;a title="The essence of Linq - MiniLinq - Channel9" href="http://channel9.msdn.com/Shows/Going+Deep/Bart-De-Smet-MinLINQ-The-Essence-of-LINQ" target="_blank"&gt;follow up video&lt;/a&gt;) can see that GroupJoin could almost be added to the 3 basic operators Cata, Ana and Bind. 

&lt;p&gt;GroupJoin and the other window operators can make otherwise fiddly and difficult tasks a cinch to put together. For example, those in the Finance game can now pretty much use GroupJoin to create their own VWAP and TWAP extension methods. Nice!&lt;/p&gt;

&lt;p&gt;The full source code is now available either via svn at &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or as a &lt;a href="http://rx-samples.googlecode.com/files/rx-samples_v009.zip"&gt;zip file&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Back to the &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;contents&lt;/a&gt; page for &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions for .NET Introduction&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Back to the previous post; &lt;a title="Part 8 - Testing Rx - Lee Campbell" href="http://leecampbell.blogspot.com/2010/10/rx-part-8-testing-rx.html"&gt;Rx Part 8 - Testing Rx&lt;/a&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:08d0ad63-e148-4b19-a1f8-76b606922211" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-5316270593235637413?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/5316270593235637413/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=5316270593235637413' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5316270593235637413'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5316270593235637413'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2011/03/rx-part-9join-window-buffer-and-group.html' title='Rx Part 9–Join, Window, Buffer and Group Join'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh4.ggpht.com/_aee9WmSAaWE/TX3C2bp92oI/AAAAAAAACpU/IvhFjhbZZd4/s72-c/wlEmoticon-smile%5B2%5D.png?imgmax=800' height='72' width='72'/><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-1807406150128123727</id><published>2011-02-20T17:07:00.001Z</published><updated>2011-02-20T17:07:19.615Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><title type='text'>Changes to the Rx API</title><content type='html'>&lt;p&gt;Readers of the &lt;a title="Reactive Extensions for .NET - An introduction" href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions series&lt;/a&gt; on this blog will have noticed recently that not all of the code always works* if you download the &lt;a title="DevLabs: Reactive Extensions for .NET (Rx)" href="http://msdn.microsoft.com/en-us/devlabs/ee794896" target="_blank"&gt;Rx assemblies&lt;/a&gt; and then copy the code off the blog. This is due to the quite frequent changes to the API. I personally have 7 different versions of the libraries and I don’t think I have downloaded them all as they have been released! Also the blog post were started all the way back in May 2010 so it is fair that there has been some movement in the API&lt;/p&gt;  &lt;p&gt;*If you get the code from the &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or as a &lt;a href="http://rx-samples.googlecode.com/files/rx-samples_v008.zip"&gt;zip file&lt;/a&gt; then it will work, as the correct version of the assembly is included.&lt;/p&gt;  &lt;p&gt;For fun I thought I would try to exercise my LINQ skills and write a quick diff tool so I can see what on the public API is actually changing on me. I threw this class together in LinqPad&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; AssemblyDiff
{
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; _oldAssemblyPath;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; _newAssemblyPath;
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; AssemblyDiff(&lt;span class="kwrd"&gt;string&lt;/span&gt; oldAssemblyPath, &lt;span class="kwrd"&gt;string&lt;/span&gt; newAssemblyPath)
    {
        _oldAssemblyPath = oldAssemblyPath;
        _newAssemblyPath = newAssemblyPath;
    }
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;String&amp;gt; NewMethodNames()
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; MethodNameDelta(GetDeclaredMethods(_newAssemblyPath), GetDeclaredMethods(_oldAssemblyPath));
    }
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;String&amp;gt; DeprecatedMethodNames()
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; MethodNameDelta(GetDeclaredMethods(_oldAssemblyPath), GetDeclaredMethods(_newAssemblyPath));
    }
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;String&amp;gt; MethodNameDelta(IEnumerable&amp;lt;MethodInfo&amp;gt; original, IEnumerable&amp;lt;MethodInfo&amp;gt; modified)
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; from methodName &lt;span class="kwrd"&gt;in&lt;/span&gt; original.Select(MethodName).Except(modified.Select(MethodName))
                    orderby methodName
                    select methodName;
    }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;MethodInfo&amp;gt; NewMethods()
    {
        var oldMethods = GetDeclaredMethods(_oldAssemblyPath);
        var currentMethods = GetDeclaredMethods(_newAssemblyPath);
        
        &lt;span class="kwrd"&gt;return&lt;/span&gt; MethodDelta(oldMethods, currentMethods);
    }
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;MethodInfo&amp;gt; DeprecatedMethods()
    {
        var oldMethods = GetDeclaredMethods(_oldAssemblyPath);
        var currentMethods = GetDeclaredMethods(_newAssemblyPath);
        
        &lt;span class="kwrd"&gt;return&lt;/span&gt; MethodDelta(currentMethods, oldMethods);
    }
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;MethodInfo&amp;gt; MethodDelta(IEnumerable&amp;lt;MethodInfo&amp;gt; original, IEnumerable&amp;lt;MethodInfo&amp;gt; changed)
    {
        var existingTypes = original.Select(m =&amp;gt; m.ReflectedType.FullName)
                                        .Distinct()
                                        .ToList();
        
        &lt;span class="kwrd"&gt;return&lt;/span&gt; from method &lt;span class="kwrd"&gt;in&lt;/span&gt; changed.Except(original, &lt;span class="kwrd"&gt;new&lt;/span&gt; MethodSignatureComparer())
                &lt;span class="kwrd"&gt;where&lt;/span&gt; existingTypes.Contains(method.ReflectedType.FullName)
                orderby method.ReflectedType.Name, method.Name
                select method;
    }
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;Type&amp;gt; NewTypes()
    {
        var currentTypes = GetTypes(_newAssemblyPath);
        var oldTypes = GetTypes(_oldAssemblyPath);
        
        &lt;span class="kwrd"&gt;return&lt;/span&gt; from type &lt;span class="kwrd"&gt;in&lt;/span&gt; currentTypes
                &lt;span class="kwrd"&gt;where&lt;/span&gt; !oldTypes.Select (t =&amp;gt; t.FullName).Contains(type.FullName)
                select type;
    }
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;Type&amp;gt; DeprecatedTypes()
    {
        var currentTypes = GetTypes(_newAssemblyPath);
        var oldTypes = GetTypes(_oldAssemblyPath);
        
        &lt;span class="kwrd"&gt;return&lt;/span&gt; from type &lt;span class="kwrd"&gt;in&lt;/span&gt; oldTypes
                &lt;span class="kwrd"&gt;where&lt;/span&gt; !currentTypes.Select (t =&amp;gt; t.FullName).Contains(type.FullName)
                select type;
    }
    
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;MethodInfo&amp;gt; GetAllMethods(&lt;span class="kwrd"&gt;string&lt;/span&gt; path)
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt;  from type &lt;span class="kwrd"&gt;in&lt;/span&gt; GetTypes(path)
                from method &lt;span class="kwrd"&gt;in&lt;/span&gt; type.GetMethods()
                &lt;span class="kwrd"&gt;where&lt;/span&gt; method.IsPublic
                select method;
    }
    
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;MethodInfo&amp;gt; GetDeclaredMethods(&lt;span class="kwrd"&gt;string&lt;/span&gt; path)
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; GetAllMethods(path).Where(method =&amp;gt; method.DeclaringType == method.ReflectedType);
    }
    
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;Type&amp;gt; GetTypes(&lt;span class="kwrd"&gt;string&lt;/span&gt; path)
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt;  from file &lt;span class="kwrd"&gt;in&lt;/span&gt; Directory.EnumerateFiles(path, &lt;span class="str"&gt;&amp;quot;*.dll&amp;quot;&lt;/span&gt;)
                from module &lt;span class="kwrd"&gt;in&lt;/span&gt; Assembly.LoadFrom(file).GetModules()
                from type &lt;span class="kwrd"&gt;in&lt;/span&gt; module.GetTypes()
                &lt;span class="kwrd"&gt;where&lt;/span&gt; type.IsPublic
                select type;
    }
    
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; MethodName(MethodInfo m)
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0}.{1}&amp;quot;&lt;/span&gt;, m.ReflectedType.Name, m.Name);
    }
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; MethodSignature(MethodInfo m)
    {
        &lt;span class="rem"&gt;//return m.ToString();&lt;/span&gt;
        var ps = m.GetParameters();
        var args = ps.Select(p=&amp;gt;ParameterSignature(p, ps.Length));
        var argsDemlimted = &lt;span class="kwrd"&gt;string&lt;/span&gt;.Join(&lt;span class="str"&gt;&amp;quot;,&amp;quot;&lt;/span&gt;, args);
        
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0} {1}.{2}({3})&amp;quot;&lt;/span&gt;, m.ReturnType.Name, m.ReflectedType.Name, m.Name, argsDemlimted);
    }
        
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; ParameterSignature(ParameterInfo parameter, &lt;span class="kwrd"&gt;int&lt;/span&gt; parameterCount)
    {
        var modifier = &lt;span class="str"&gt;&amp;quot;&amp;quot;&lt;/span&gt;;&lt;span class="rem"&gt;//out/ref/params/&lt;/span&gt;
        var defaultValue = &lt;span class="str"&gt;&amp;quot;&amp;quot;&lt;/span&gt;;
        &lt;span class="kwrd"&gt;if&lt;/span&gt;(parameter.IsOut) modifier = &lt;span class="str"&gt;&amp;quot;out &amp;quot;&lt;/span&gt;;
        &lt;span class="kwrd"&gt;if&lt;/span&gt;(parameter.IsOptional)
        {
            modifier = &lt;span class="str"&gt;&amp;quot;optional &amp;quot;&lt;/span&gt;;
            defaultValue = parameter.DefaultValue.ToString();
        }
        &lt;span class="kwrd"&gt;if&lt;/span&gt;(parameter.IsRetval) modifier += &lt;span class="str"&gt;&amp;quot;isretval &amp;quot;&lt;/span&gt;;
        &lt;span class="kwrd"&gt;if&lt;/span&gt;(parameter.IsIn) modifier += &lt;span class="str"&gt;&amp;quot;IsIn &amp;quot;&lt;/span&gt;;
        &lt;span class="kwrd"&gt;if&lt;/span&gt;(parameter.IsLcid) modifier += &lt;span class="str"&gt;&amp;quot;IsLcid &amp;quot;&lt;/span&gt;;
        &lt;span class="kwrd"&gt;if&lt;/span&gt;(parameter.Position== parameterCount-1 &amp;amp;&amp;amp; parameter.ParameterType.IsArray)
        {
            modifier = &lt;span class="str"&gt;&amp;quot;params &amp;quot;&lt;/span&gt;;
        }
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;.Format(&lt;span class="str"&gt;&amp;quot;{0}{1}{2}&amp;quot;&lt;/span&gt;, modifier,parameter.Name, defaultValue);
    }
    
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MethodSignatureComparer : IEqualityComparer&amp;lt;MethodInfo&amp;gt;
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; Equals(MethodInfo lhs, MethodInfo rhs)
        {                
            &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;.Equals(lhs.ToString(), rhs.ToString());
        }
        
        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; GetHashCode(MethodInfo method)
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; method.ToString().GetHashCode();
        }
    }
}&lt;/pre&gt;

&lt;p&gt;and then I used it like this &lt;/p&gt;

&lt;pre class="csharpcode"&gt;var old =         &lt;span class="str"&gt;@&amp;quot;C:\Program Files\Microsoft Cloud Programmability\Reactive Extensions\v1.0.2787.0\Net4&amp;quot;&lt;/span&gt;;
var current =     &lt;span class="str"&gt;@&amp;quot;C:\Program Files\Microsoft Cloud Programmability\Reactive Extensions\v1.0.2838.0\Net4&amp;quot;&lt;/span&gt;;

var dllDiff = &lt;span class="kwrd"&gt;new&lt;/span&gt; AssemblyDiff(old, current);

&lt;span class="str"&gt;&amp;quot;New Methods&amp;quot;&lt;/span&gt;.Dump();
dllDiff.NewMethodNames().Dump();
&lt;span class="str"&gt;&amp;quot;Deprecated Methods&amp;quot;&lt;/span&gt;.Dump();
dllDiff.DeprecatedMethodNames().Dump();
&lt;span class="str"&gt;&amp;quot;New Types&amp;quot;&lt;/span&gt;.Dump();
dllDiff.NewTypes().Select (t =&amp;gt; t.FullName).Dump();
&lt;span class="str"&gt;&amp;quot;Deprecated Types&amp;quot;&lt;/span&gt;.Dump();
dllDiff.DeprecatedTypes().Select (t =&amp;gt; t.FullName).Dump();
&lt;span class="str"&gt;&amp;quot;New overloads&amp;quot;&lt;/span&gt;.Dump();
dllDiff.NewMethods().Select(AssemblyDiff.MethodSignature).Dump();
&lt;span class="str"&gt;&amp;quot;Deprecated overloads&amp;quot;&lt;/span&gt;.Dump();
dllDiff.DeprecatedMethods().Select(AssemblyDiff.MethodSignature).Dump();&lt;/pre&gt;

&lt;p&gt;and I get this neat output.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;New Methods (7 Items)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;ConnectableObservable`2.Connect&lt;/li&gt;

  &lt;li&gt;ConnectableObservable`2.Subscribe&lt;/li&gt;

  &lt;li&gt;Observable.GroupJoin&lt;/li&gt;

  &lt;li&gt;Observable.Multicast&lt;/li&gt;

  &lt;li&gt;Observable.Window&lt;/li&gt;

  &lt;li&gt;Qbservable.GroupJoin&lt;/li&gt;

  &lt;li&gt;Qbservable.Window&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Deprecated Methods (6 Items)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;ConnectableObservable`1.Connect&lt;/li&gt;

  &lt;li&gt;ConnectableObservable`1.Subscribe&lt;/li&gt;

  &lt;li&gt;Observable.Prune&lt;/li&gt;

  &lt;li&gt;Observable.Replay&lt;/li&gt;

  &lt;li&gt;Qbservable.Prune&lt;/li&gt;

  &lt;li&gt;Qbservable.Replay&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;New Types (1 Item)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;System.Collections.Generic.ConnectableObservable`2&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Deprecated Types (0 Items)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;New Overloads (30 Items)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;IEnumerable`1 EnumerableEx.Generate(initialState,condition,iterate,resultSelector)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTime(source,timeSpan,timeShift,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTime(source,timeSpan,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTime(source,timeSpan,timeShift)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTime(source,timeSpan)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTimeOrCount(source,timeSpan,count,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTimeOrCount(source,timeSpan,count)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.GroupJoin(left,right,leftDurationSelector,rightDurationSelector,resultSelector)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.If(condition,thenSource)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Join(left,right,leftDurationSelector,rightDurationSelector,resultSelector)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Multicast(source,subject)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source,subject)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source,subject,selector)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Window(source,windowOpenings,windowClosingSelector)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Window(source,windowClosingSelector,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Window(source,windowClosingSelector)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTime(source,timeSpan,timeShift,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTime(source,timeSpan,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTime(source,timeSpan,timeShift)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTime(source,timeSpan)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTimeOrCount(source,timeSpan,count,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTimeOrCount(source,timeSpan,count)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.GroupJoin(left,right,leftDurationSelector,rightDurationSelector,resultSelector)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.If(provider,condition,thenSource)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Join(left,right,leftDurationSelector,rightDurationSelector,resultSelector)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source,subject,selector)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source,subject)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Window(source,windowOpenings,windowClosingSelector)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Window(source,windowClosingSelector,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Window(source,windowClosingSelector)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Deprecated overloads (71 Items)&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;IEnumerable`1 EnumerableEx.Generate(initialState,condition,resultSelector,iterate)&lt;/li&gt;

  &lt;li&gt;IEnumerable`1 EnumerableEx.Generate(function)&lt;/li&gt;

  &lt;li&gt;IEnumerable`1 EnumerableEx.Generate(initialState,resultSelector,iterate)&lt;/li&gt;

  &lt;li&gt;IEnumerable`1 EnumerableEx.Generate(initial,resultSelector,iterate)&lt;/li&gt;

  &lt;li&gt;IEnumerable`1 EnumerableEx.Generate(initial,condition,resultSelector,iterate)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTime(source,timeSpan,timeShift,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTime(source,timeSpan,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTime(source,timeSpan,timeShift)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTime(source,timeSpan)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTimeOrCount(source,timeSpan,count,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.BufferWithTimeOrCount(source,timeSpan,count)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Prune(source)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Prune(source,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Prune(source,selector)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Prune(source,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source1,source2,selector)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source1,source2,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source1,source2,source3,selector)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source1,source2,source3,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source1,source2,source3,source4,selector)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source1,source2,source3,source4,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Publish(source,initialValue)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Publish(source,initialValue,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source,selector,initialValue)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source,selector,initialValue,scheduler)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Publish(source)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Publish(source,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source,selector)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Publish(source,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Replay(source)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Replay(source,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Replay(source,selector)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Replay(source,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Replay(source,window)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Replay(source,selector,window)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Replay(source,window,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Replay(source,selector,window,scheduler)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Replay(source,bufferSize,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Replay(source,selector,bufferSize,scheduler)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Replay(source,bufferSize)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Replay(source,selector,bufferSize)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Replay(source,bufferSize,window)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Replay(source,selector,bufferSize,window)&lt;/li&gt;

  &lt;li&gt;IConnectableObservable`1 Observable.Replay(source,bufferSize,window,scheduler)&lt;/li&gt;

  &lt;li&gt;IObservable`1 Observable.Replay(source,selector,bufferSize,window,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTime(source,timeSpan,timeShift,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTime(source,timeSpan,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTime(source,timeSpan,timeShift)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTime(source,timeSpan)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTimeOrCount(source,timeSpan,count,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.BufferWithTimeOrCount(source,timeSpan,count)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Prune(source,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Prune(source,selector)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source,selector,initialValue)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source,selector,initialValue,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source,selector)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source1,source2,selector)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source1,source2,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source1,source2,source3,selector)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source1,source2,source3,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source1,source2,source3,source4,selector)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Publish(source1,source2,source3,source4,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Replay(source,selector,bufferSize)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Replay(source,selector,bufferSize,window)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Replay(source,selector,bufferSize,window,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Replay(source,selector)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Replay(source,selector,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Replay(source,selector,window)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Replay(source,selector,window,scheduler)&lt;/li&gt;

  &lt;li&gt;IQbservable`1 Qbservable.Replay(source,selector,bufferSize,scheduler)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;From memory Generate has been a constant source of change which has confused some readers that are using different versions of the library to what the Part 2 post was done with. This diff script&amp;#160; goes to show that it is still undergoing changes &lt;/p&gt;

&lt;p&gt;&lt;img style="border-bottom-style: none; border-right-style: none; border-top-style: none; border-left-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://lh3.ggpht.com/_aee9WmSAaWE/TWFKRkZTYUI/AAAAAAAACpE/HyPdZ-DrJ6s/wlEmoticon-smile%5B2%5D.png?imgmax=800" /&gt;&lt;/p&gt;

&lt;p&gt;Links:&lt;/p&gt;

&lt;p&gt;&lt;a title="Reactive Extensions for .NET -An Introduction" href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions for .NET an Introduction&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a title="DevLabs: Reactive Extensions for .NET (Rx)" href="http://msdn.microsoft.com/en-us/devlabs/ee794896"&gt;DevLabs: Reactive Extensions for .NET (Rx)&lt;/a&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-1807406150128123727?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/1807406150128123727/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=1807406150128123727' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/1807406150128123727'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/1807406150128123727'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2011/02/changes-to-rx-api.html' title='Changes to the Rx API'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://lh3.ggpht.com/_aee9WmSAaWE/TWFKRkZTYUI/AAAAAAAACpE/HyPdZ-DrJ6s/s72-c/wlEmoticon-smile%5B2%5D.png?imgmax=800' height='72' width='72'/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-7651018892620246502</id><published>2011-02-13T15:02:00.002Z</published><updated>2011-02-20T16:26:12.906Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Code Quality'/><title type='text'>Silverlight testing</title><content type='html'>&lt;p&gt;I am putting this out there to see if I can get some traction with other Test Driven Silverlight coders out there. If you are one of these people you will know of the strife your day-to-day coding. For those who don't know what I mean these are the three options a Silverlight developer has with regards to test driven coding: &lt;/p&gt;  &lt;p&gt;1) Use the &lt;a href="http://code.msdn.microsoft.com/silverlightut"&gt;Silverlight Unit Test Framework&lt;/a&gt;. The problem with this is that you lose any integrated development support, it is amazingly slow (in the area of 1-5 tests per second), and doesn't have any useful build tool support (coverage, TFS, TeamCity). Massive Fail. &lt;/p&gt;  &lt;p&gt;2) Cross compile to .NET 4 all of your Models, ViewModels, Controllers, Modules, Presenters (i.e. everything that is not a View or a Control). Now write unit tests against this project. This means you get back to fast tests (100s tests per second) but take a hit on compiling twice and managing the project linking and just having twice as many projects floating around. &lt;/p&gt;  &lt;p&gt;3) What I imagine as the most popular option, just don't write any tests. &lt;/p&gt;  &lt;p&gt;Looking at what most of the requests are for, tells me most people are using Silverlight for Marketing websites to stream rich content. Business applications have yet to stake any dominance. What I am hoping that anyone reading this will if they feel my pain, just go to &lt;a href="http://dotnet.uservoice.com/forums/4325-silverlight-feature-suggestions/suggestions/313397-unit-testing-integrated-in-visual-studio-and-msbui?ref=title"&gt;this link&lt;/a&gt; and vote. It seems that these polls really have an effect; DataTemplates appear to be part of SL 5 due to massive demand. I am hoping that Microsoft can focus on getting the underlying framework right before they go off and give us a 3D-multitouch-proximity aware API :) &lt;/p&gt;  &lt;p&gt;&lt;a href="http://dotnet.uservoice.com/forums/4325-silverlight-feature-suggestions/suggestions/313397-unit-testing-integrated-in-visual-studio-and-msbui?ref=title"&gt;http://dotnet.uservoice.com/forums/4325-silverlight-feature-suggestions/suggestions/313397-unit-testing-integrated-in-visual-studio-and-msbui?ref=title&lt;/a&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-7651018892620246502?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/7651018892620246502/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=7651018892620246502' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7651018892620246502'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7651018892620246502'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2011/02/silverlight-testing.html' title='Silverlight testing'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-3693790943569209176</id><published>2010-11-02T14:16:00.003Z</published><updated>2010-12-06T20:27:46.014Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='Concurrency'/><category scheme='http://www.blogger.com/atom/ns#' term='Code Quality'/><title type='text'>Rx design guidelines</title><content type='html'>The Rx team have released a pdf specifiying their Design Guidelines to use when coding with the Reactive Extentions.

The original post is here
&lt;a href="http://blogs.msdn.com/b/rxteam/archive/2010/10/28/rx-design-guidelines.aspx"&gt;http://blogs.msdn.com/b/rxteam/archive/2010/10/28/rx-design-guidelines.aspx&lt;/a&gt;
The PDF is here
&lt;a href="http://go.microsoft.com/fwlink/?LinkID=205219"&gt;http://go.microsoft.com/fwlink/?LinkID=205219&lt;/a&gt;

Great stuff. Next; the FxCop rules for static analysis?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-3693790943569209176?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/3693790943569209176/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=3693790943569209176' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/3693790943569209176'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/3693790943569209176'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/11/rx-design-guidelines.html' title='Rx design guidelines'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-3226080342334616352</id><published>2010-10-26T08:38:00.003+01:00</published><updated>2011-03-14T07:59:49.139Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='Concurrency'/><category scheme='http://www.blogger.com/atom/ns#' term='Code Quality'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Rx Part 8 - Testing Rx</title><content type='html'>&lt;p&gt;Having &lt;a title="Part 6 - Scheduling and Threading in Rx" href="http://leecampbell.blogspot.com/2010/06/rx-part-6-scheduling-and-threading.html" target="_blank"&gt;reviewed the scheduling&lt;/a&gt; available to us in Rx and now that we are aware of &lt;a title="Part 7 - Hot and Cold Observables" href="http://leecampbell.blogspot.com/2010/08/rx-part-7-hot-and-cold-observables.html" target="_blank"&gt;Hot and Cold observables&lt;/a&gt; we have almost enough skills in our tool belt to start using Rx in anger. However many developers wouldn’t dream of starting coding without first being able to write tests to prove their code is in fact satisfying their requirements and providing them with that safety net against regression. Rx poses some interesting problems to our Test Driven community&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Scheduling and therefore Threading are generally avoided in test scenarios as they can introduce race conditions which may lead to non-deterministic tests. &lt;/li&gt;    &lt;li&gt;Tests should run as fast as possible. &lt;/li&gt;    &lt;li&gt;Rx is a new technology/library so naturally as we master it, we will refactor our code. We want to use to tests to ensure our refactoring have not altered the internal behaviour of our code base. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So we want to test our code but don't want to introduce false-negatives, false-positives or non-deterministic tests. Also if we look at the Rx library there are plenty of methods that involve Scheduling so it is hard to ignore. This Linq query shows us that there are at least 32 extension methods that accept an IScheduler as a parameter&lt;/p&gt;  &lt;pre class="csharpcode"&gt;var query = from method &lt;span class="kwrd"&gt;in&lt;/span&gt; &lt;span class="kwrd"&gt;typeof&lt;/span&gt; (Observable).GetMethods()
        from parameter &lt;span class="kwrd"&gt;in&lt;/span&gt; method.GetParameters()
        &lt;span class="kwrd"&gt;where&lt;/span&gt; &lt;span class="kwrd"&gt;typeof&lt;/span&gt; (IScheduler).IsAssignableFrom(parameter.ParameterType)
        group method by method.Name into m
        orderby m.Key
        select m.Key;
            
query.Run(Console.WriteLine);
&lt;span class="rem"&gt;/* &lt;/span&gt;
&lt;span class="rem"&gt;BufferWithTime, Catch, Concat, Delay, Empty, Generate, GenerateWithTime, Interval&lt;/span&gt;
&lt;span class="rem"&gt;Merge, ObserveOn, OnErrorResumeNext, Prune, Publish, Range, Repeat, Replay&lt;/span&gt;
&lt;span class="rem"&gt;Retry, Return, Sample, Start, StartWith, Subscribe, SubscribeOn, Take, Throttle&lt;/span&gt;
&lt;span class="rem"&gt;Throw, TimeInterval, Timeout, Timer, Timestamp, ToAsync, ToObservable&lt;/span&gt;
&lt;span class="rem"&gt;*/&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;There are some methods that we already will be familiar with such as ObserveOn and SubscribeOn. Then there are others that will optionally take an IScheduler in one of the method overloads. TDD/TestFirst coders will want to opt for the overload that takes the IScheduler so that we can have some control over scheduling in our tests.&lt;/p&gt;

&lt;p&gt;In this example we create a stream that publishes values every second for 5 seconds. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;var interval = Observable
    .Interval(TimeSpan.FromSeconds(1))
    .Take(5);&lt;/pre&gt;

&lt;p&gt;If we to write a test that ensured that we received 5 values and they were each 1 second apart it would take 5 seconds. That would be no good, I want hundreds if not thousands of tests to run in 5 seconds. A more common time related example that would need tests is setting a timeout.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var stream = Observable.Never&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();

var exceptionThrown = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
stream.Timeout(TimeSpan.FromMinutes(1))
    .Run(
        i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;This will never run.&amp;quot;&lt;/span&gt;),
        ex =&amp;gt; exceptionThrown = &lt;span class="kwrd"&gt;true&lt;/span&gt;);
Assert.IsTrue(exceptionThrown);&lt;/pre&gt;

&lt;p&gt;This test would take 1 minute to run. However if we did some test first code in this style, where we added the timeout after the test, running the test initially to fail (Red-Green-Refactor) would never complete. Hmmmm…..&lt;/p&gt;

&lt;h4&gt;TestScheduler&lt;/h4&gt;

&lt;p&gt;To our rescue comes the TestScheduler. This is a recent addition to the Rx library that takes the concept of a virtual scheduler to allow us emulate and control time. Cool.&lt;/p&gt;

&lt;p&gt;The concept of a virtual scheduler can sort of be thought of a queue of actions to be executed that are each marked with the point in time they should be executed. Where actions are attempted to be scheduled at the same “time” the second collision will be scheduled or queued after the first action but marked as with the same point in “time” . When we use the TestScheduler we can either “drain the queue” by calling run which will execute all scheduled actions, or we can specify to run all tasks up to a point in time.&lt;/p&gt;

&lt;p&gt;In this example we schedule a task on to the queue to be run immediately by using the simple overload. We then execute everything scheduled for the first tick (ie the first action).&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var scheduler = &lt;span class="kwrd"&gt;new&lt;/span&gt; TestScheduler();
var wasExecuted = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
scheduler.Schedule(() =&amp;gt; wasExecuted = &lt;span class="kwrd"&gt;true&lt;/span&gt;);
Assert.IsFalse(wasExecuted);
scheduler.RunTo(1);         &lt;span class="rem"&gt;//execute 1 tick of queued actions&lt;/span&gt;
Assert.IsTrue(wasExecuted);&lt;/pre&gt;

&lt;p&gt;The TestScheduler type is actually an implementation of the abstract VirtualScheduler&amp;lt;TAbsolute, TRelative&amp;gt; where the TestSchuduler specifies long for both TAbsolute and TRelative. The net result is that the TestScheduler interface looks something like this&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; TestScheduler
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; TestScheduler();

    &lt;span class="rem"&gt;// Methods&lt;/span&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;long&lt;/span&gt; FromTimeSpan(TimeSpan timeSpan);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;long&lt;/span&gt; Increment(&lt;span class="kwrd"&gt;long&lt;/span&gt; absolute, &lt;span class="kwrd"&gt;long&lt;/span&gt; relative);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Run();
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; RunTo(&lt;span class="kwrd"&gt;long&lt;/span&gt; time);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IDisposable Schedule(Action action);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IDisposable Schedule(Action action, TimeSpan dueTime);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IDisposable Schedule(Action action, &lt;span class="kwrd"&gt;long&lt;/span&gt; dueTime);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Sleep(&lt;span class="kwrd"&gt;long&lt;/span&gt; ticks);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; DateTimeOffset ToDateTimeOffset(&lt;span class="kwrd"&gt;long&lt;/span&gt; absolute);

    &lt;span class="rem"&gt;// Properties&lt;/span&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; DateTimeOffset Now { get; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;long&lt;/span&gt; Ticks { get; }
}&lt;/pre&gt;

&lt;p&gt;We should already be familiar with what the Schedule methods would do, the other method of interest for this post are the Run() and RunTo(long) methods. Run() will just execute all the actions that have been scheduled. RunTo(long) will execute all the actions that have been scheduled up to the time specified by the long value which represents ticks in this case. Having a quick look into the implementations for Schedule, RunTo and Run give us the insight we need to really understand the virtual schedulers.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; IDisposable Schedule(Action action)
{
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.Schedule(action, TimeSpan.Zero);
}
&lt;span class="kwrd"&gt;public&lt;/span&gt; IDisposable Schedule(Action action, TimeSpan dueTime)
{
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.Schedule(action, &lt;span class="kwrd"&gt;this&lt;/span&gt;.FromTimeSpan(dueTime));
}
&lt;span class="kwrd"&gt;public&lt;/span&gt; IDisposable Schedule(Action action, TRelative dueTime)
{
    BooleanDisposable disposable = &lt;span class="kwrd"&gt;new&lt;/span&gt; BooleanDisposable();
    TAbsolute local = &lt;span class="kwrd"&gt;this&lt;/span&gt;.Increment(&lt;span class="kwrd"&gt;this&lt;/span&gt;.Ticks, dueTime);
    Action action2 = &lt;span class="kwrd"&gt;delegate&lt;/span&gt; {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (!disposable.IsDisposed)
        {
            action();
        }
    };
    ScheduledItem&amp;lt;TAbsolute&amp;gt; item = &lt;span class="kwrd"&gt;new&lt;/span&gt; ScheduledItem&amp;lt;TAbsolute&amp;gt;(action2, local);
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.queue.Enqueue(item);
    &lt;span class="kwrd"&gt;return&lt;/span&gt; disposable;
}

&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; RunTo(TAbsolute time)
{
    &lt;span class="kwrd"&gt;while&lt;/span&gt; ((&lt;span class="kwrd"&gt;this&lt;/span&gt;.queue.Count &amp;gt; 0) &amp;amp;&amp;amp; (&lt;span class="kwrd"&gt;this&lt;/span&gt;.queue.Peek().DueTime.CompareTo(time) &amp;lt;= 0))
    {
        ScheduledItem&amp;lt;TAbsolute&amp;gt; item = &lt;span class="kwrd"&gt;this&lt;/span&gt;.queue.Dequeue();
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.Ticks = item.DueTime;
        item.Action();
    }
}

&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Run()
{
    &lt;span class="kwrd"&gt;while&lt;/span&gt; (&lt;span class="kwrd"&gt;this&lt;/span&gt;.queue.Count &amp;gt; 0)
    {
        ScheduledItem&amp;lt;TAbsolute&amp;gt; item = &lt;span class="kwrd"&gt;this&lt;/span&gt;.queue.Dequeue();
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.Ticks = item.DueTime;
        item.Action();
    }
}&lt;/pre&gt;

&lt;p&gt;Obviously this is the internal implementation and would be subject to change, however as the documentation currently is quite weak for the VirtualScheduler and TestScheduler I think this use of reflection is helpful. This example should clear up what happens when items are scheduled at the same time.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var scheduler = &lt;span class="kwrd"&gt;new&lt;/span&gt; TestScheduler();
&lt;span class="kwrd"&gt;long&lt;/span&gt; dueTime = 4L;
scheduler.Schedule(() =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;1&amp;quot;&lt;/span&gt;), dueTime);
scheduler.Schedule(() =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;2&amp;quot;&lt;/span&gt;), dueTime);
scheduler.Schedule(() =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;3&amp;quot;&lt;/span&gt;), dueTime+1);
scheduler.Schedule(() =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;4&amp;quot;&lt;/span&gt;), dueTime+1);
Console.WriteLine(&lt;span class="str"&gt;&amp;quot;RunTo(dueTime)&amp;quot;&lt;/span&gt;);
scheduler.RunTo(dueTime); 
Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Run()&amp;quot;&lt;/span&gt;);
scheduler.Run();
&lt;span class="rem"&gt;/* Output:&lt;/span&gt;
&lt;span class="rem"&gt;RunTo(dueTime)&lt;/span&gt;
&lt;span class="rem"&gt;1&lt;/span&gt;
&lt;span class="rem"&gt;2&lt;/span&gt;
&lt;span class="rem"&gt;Run()&lt;/span&gt;
&lt;span class="rem"&gt;3&lt;/span&gt;
&lt;span class="rem"&gt;4&lt;/span&gt;
&lt;span class="rem"&gt;*/&lt;/span&gt;&lt;/pre&gt;

&lt;h4&gt;Testing Rx code&lt;/h4&gt;

&lt;p&gt;Now that we have learnt a little bit about the TestScheduler, lets look at how we could use it to get our 2 initial code snippets (Interval and TimeOut) to execute as fast as possible but still maintaining the semantics of time. In this example we generate our 5 values one second apart but pass in our TestScheduler to the Interval method.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[TestMethod]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Testing_with_test_scheduler()
{
    var scheduler = &lt;span class="kwrd"&gt;new&lt;/span&gt; TestScheduler();
    var interval = Observable
        .Interval(TimeSpan.FromSeconds(1), scheduler)
        .Take(5);

    &lt;span class="kwrd"&gt;bool&lt;/span&gt; isComplete = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
    interval.Subscribe(Console.WriteLine, () =&amp;gt; isComplete = &lt;span class="kwrd"&gt;true&lt;/span&gt;);

    scheduler.Run();

    Assert.IsTrue(isComplete); &lt;span class="rem"&gt;//Executes in less than 0.01s &amp;quot;on my machine&amp;quot;&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;While this is mildly interesting, what I think is more important is how we would test a real piece of code. Imagine if you will a Presenter that subscribes to a stream of prices. As prices are published it adds them to a ViewModel. Assuming this is a WPF or Silverlight implementation we take the liberty of enforcing that the subscription be done on the ThreadPool and the observing is executed on the Dispatcher.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MyPresenter
{
...
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Show(&lt;span class="kwrd"&gt;string&lt;/span&gt; symbol)
    {
        _myService.PriceStream(symbol)
                                    .SubscribeOn(Scheduler.ThreadPool)
                                    .ObserveOn(Scheduler.Dispatcher)
                                    .Subscribe(price=&amp;gt;_viewModel.Prices.Add(price));
    }
...
}&lt;/pre&gt;

&lt;p&gt;While this snippet of code may do what we want it to do, it will be hard to test as it is accessing the schedulers via static properties. To help my testing, I have created my own interface that exposes the same IScheduler implementations that the Scheduler type does.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; ISchedulerService
{
    IScheduler CurrentThread { get; }
    IScheduler Dispatcher { get; }
    IScheduler Immediate { get; }
    IScheduler NewThread { get; }
    IScheduler ThreadPool { get; }
    &lt;span class="rem"&gt;//IScheduler TaskPool { get; }&lt;/span&gt;
}
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;sealed&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; SchedulerService : ISchedulerService
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IScheduler CurrentThread { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; Scheduler.CurrentThread; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IScheduler Dispatcher { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; Scheduler.Dispatcher; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IScheduler Immediate { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; Scheduler.Immediate; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IScheduler NewThread { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; Scheduler.NewThread; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IScheduler ThreadPool { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; Scheduler.ThreadPool; } }

    &lt;span class="rem"&gt;//public IScheduler TaskPool { get { return Scheduler.TaskPool; } }&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;This now allows me to inject an ISchedulerService which gives me a seam to help my testing. I can now write some tests for my Presenter.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[TestInitialize]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetUp()
{
    _myServiceMock = &lt;span class="kwrd"&gt;new&lt;/span&gt; Mock&amp;lt;IMyService&amp;gt;();
    _viewModelMock = &lt;span class="kwrd"&gt;new&lt;/span&gt; Mock&amp;lt;IViewModel&amp;gt;();
    _schedulerService = &lt;span class="kwrd"&gt;new&lt;/span&gt; TestSchedulers();

    var prices = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObservableCollection&amp;lt;&lt;span class="kwrd"&gt;decimal&lt;/span&gt;&amp;gt;();
    _viewModelMock.SetupGet(vm =&amp;gt; vm.Prices).Returns(prices);
    _viewModelMock.SetupProperty(vm =&amp;gt; vm.IsConnected);
}

[TestMethod]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Should_pass_symbol_to_MyService_PriceStream()
{
    var expected = &lt;span class="str"&gt;&amp;quot;SomeSymbol&amp;quot;&lt;/span&gt;;
    var priceStream = &lt;span class="kwrd"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="kwrd"&gt;decimal&lt;/span&gt;&amp;gt;();
    _myServiceMock.Setup(svc =&amp;gt; svc.PriceStream(It.Is&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;(symbol=&amp;gt;symbol==expected))).Returns(priceStream);

    var sut = &lt;span class="kwrd"&gt;new&lt;/span&gt; MyPresenter(_myServiceMock.Object, _viewModelMock.Object, _schedulerService);
    sut.Show(expected);

    _myServiceMock.Verify();
}

[TestMethod]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Should_add_to_VM_Prices_when_MyService_publishes_price()
{
    &lt;span class="kwrd"&gt;decimal&lt;/span&gt; expected = 1.23m;
    var priceStream = &lt;span class="kwrd"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="kwrd"&gt;decimal&lt;/span&gt;&amp;gt;();
    _myServiceMock.Setup(svc =&amp;gt; svc.PriceStream(It.IsAny&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;())).Returns(priceStream);

    var sut = &lt;span class="kwrd"&gt;new&lt;/span&gt; MyPresenter(_myServiceMock.Object, _viewModelMock.Object, _schedulerService);
    sut.Show(&lt;span class="str"&gt;&amp;quot;SomeSymbol&amp;quot;&lt;/span&gt;);
    _schedulerService.ThreadPool.Schedule(() =&amp;gt; priceStream.OnNext(expected));  &lt;span class="rem"&gt;//Schedule the OnNext&lt;/span&gt;
    _schedulerService.ThreadPool.RunTo(1);  &lt;span class="rem"&gt;//Execute the OnNext action&lt;/span&gt;
    _schedulerService.Dispatcher.RunTo(1);  &lt;span class="rem"&gt;//Execute the OnNext Handler (ie adding to the Prices collection)&lt;/span&gt;

    Assert.AreEqual(1, _viewModelMock.Object.Prices.Count);
    Assert.AreEqual(expected, _viewModelMock.Object.Prices.First());
}&lt;/pre&gt;

&lt;p&gt;These two tests show first a simple expectation that a string value passed to my Show(string) method will be passed to the underlying service. This is not at all relevant to Rx. The next test shows the usage of my implementation of the ISchedulerService specific for testing. It exposes all of the IScheduler properties as instances of TestSchedulers. This now allows me to inject TestSchedulers for testing which in-turn allows me to control the rate at which things are scheduled. &lt;/p&gt;

&lt;p&gt;For those of you new to Moq, some of the syntax my be a little bit confusing. Where you see a Setup(..) or SetupGet(..) method call there is just a little bit of Expression magic that tells my mocks to return correct thing when called. The .Object property hanging off my mocks are the dynamically generated implementations of the interfaces. This next test I hope you find the most interesting. Here we really get the full value out of our TestScheduler, by testing timeouts.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[TestMethod]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Should_timeout_if_no_prices_for_10_seconds()
{
    var timeoutPeriod = TimeSpan.FromSeconds(10);
    var priceStream = Observable.Never&amp;lt;&lt;span class="kwrd"&gt;decimal&lt;/span&gt;&amp;gt;();
    _myServiceMock.Setup(svc =&amp;gt; svc.PriceStream(It.IsAny&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;())).Returns(priceStream);

    var sut = &lt;span class="kwrd"&gt;new&lt;/span&gt; MyPresenter(_myServiceMock.Object, _viewModelMock.Object, _schedulerService);
    sut.Show(&lt;span class="str"&gt;&amp;quot;SomeSymbol&amp;quot;&lt;/span&gt;);

    _schedulerService.ThreadPool.RunTo(timeoutPeriod.Ticks - 1);
    Assert.IsTrue(_viewModelMock.Object.IsConnected);

    _schedulerService.ThreadPool.RunTo(timeoutPeriod.Ticks);
    Assert.IsFalse(_viewModelMock.Object.IsConnected);
}&lt;/pre&gt;

&lt;p&gt;The key points to note are:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;We return an Observable.Never for our price stream so that no prices are ever pushed and no OnComplete is published either. &lt;/li&gt;

  &lt;li&gt;The _schedulerService is a test fake that returns TestSchedulers for all of it’s schedulers &lt;/li&gt;

  &lt;li&gt;We run the ThreadPool TestScheduler up until 1 tick away from our timeout period and ensure that we have not timed out &lt;/li&gt;

  &lt;li&gt;We run the ThreadPool TestScheduler up to our timeout period and then ensure that we have timed out. &lt;/li&gt;

  &lt;li&gt;The test is sub second even though we are testing for a 10 second timeout! &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Generally I only want to have one assertion in each of my tests, but for this example I think it elegantly tests that the Timeout is for 10seconds and not longer or shorter. If I was to remove the first assertion my test would only prove that the timeout was no greater than 10 seconds but could reasonably be set to say 3 seconds. The implementation for this simple presenter is as follows&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; MyPresenter
{
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; IMyService _myService;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; IViewModel _viewModel;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; ISchedulerService _schedulerService;

    &lt;span class="kwrd"&gt;public&lt;/span&gt; MyPresenter(IMyService myService, IViewModel viewModel, ISchedulerService schedulerService)
    {
        _myService = myService;
        _schedulerService = schedulerService;
        _viewModel = viewModel;
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Show(&lt;span class="kwrd"&gt;string&lt;/span&gt; symbol)
    {
        _myService.PriceStream(symbol)
                    .SubscribeOn(_schedulerService.ThreadPool)
                    .ObserveOn(_schedulerService.Dispatcher)
                    .Timeout(TimeSpan.FromSeconds(10), _schedulerService.ThreadPool)
                    .Subscribe(OnPriceUpdate, ex =&amp;gt;
                                                    {
                                                        &lt;span class="kwrd"&gt;if&lt;/span&gt; (ex &lt;span class="kwrd"&gt;is&lt;/span&gt; TimeoutException)
                                                            _viewModel.IsConnected = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
                                                    });
        _viewModel.IsConnected = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
    }

    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; OnPriceUpdate(&lt;span class="kwrd"&gt;decimal&lt;/span&gt; price)
    {
        _viewModel.Prices.Add(price);
    }
}&lt;/pre&gt;

&lt;p&gt;I hope this post on testing helps you bring you skills that you have been developing in Rx to a level where you may be comfortable considering them for production use.&lt;/p&gt;

&lt;p&gt;For your reference here are the two test versions of the ISchedulerService I find useful. One will just schedule everything with the ImmediateScheduler and the other uses the TestSchedulers for fine grained control.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;sealed&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; TestSchedulers : ISchedulerService
{
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; TestScheduler _currentThread = &lt;span class="kwrd"&gt;new&lt;/span&gt; TestScheduler();
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; TestScheduler _dispatcher = &lt;span class="kwrd"&gt;new&lt;/span&gt; TestScheduler();
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; TestScheduler _immediate = &lt;span class="kwrd"&gt;new&lt;/span&gt; TestScheduler();
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; TestScheduler _newThread = &lt;span class="kwrd"&gt;new&lt;/span&gt; TestScheduler();
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; TestScheduler _threadPool = &lt;span class="kwrd"&gt;new&lt;/span&gt; TestScheduler();

    &lt;span class="preproc"&gt;#region&lt;/span&gt; Implementation of ISchedulerService
    IScheduler ISchedulerService.CurrentThread { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _currentThread; } }

    IScheduler ISchedulerService.Dispatcher { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _dispatcher; } }

    IScheduler ISchedulerService.Immediate { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _immediate; } }

    IScheduler ISchedulerService.NewThread { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _newThread; } }

    IScheduler ISchedulerService.ThreadPool { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _threadPool; } }
    &lt;span class="preproc"&gt;#endregion&lt;/span&gt;

    &lt;span class="kwrd"&gt;public&lt;/span&gt; TestScheduler CurrentThread { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _currentThread; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; TestScheduler Dispatcher { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _dispatcher; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; TestScheduler Immediate { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _immediate; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; TestScheduler NewThread { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _newThread; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; TestScheduler ThreadPool { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _threadPool; } }
}

&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;sealed&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ImmediateSchedulers : ISchedulerService
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IScheduler CurrentThread { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; Scheduler.Immediate; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IScheduler Dispatcher { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; Scheduler.Immediate; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IScheduler Immediate { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; Scheduler.Immediate; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IScheduler NewThread { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; Scheduler.Immediate; } }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IScheduler ThreadPool { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; Scheduler.Immediate; } }
}&lt;/pre&gt;

&lt;p&gt;The full source code is now available either via svn at &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or as a &lt;a title="rx-samples source code" href="http://rx-samples.googlecode.com/files/rx-samples_v009.zip" target="_blank"&gt;zip file&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Back to the &lt;a title="Reactive Extensions for .NET Introduction - Lee Campbell" href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;contents&lt;/a&gt; page for &lt;a title="Reactive Extensions for .NET Introduction - Lee Campbell" href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions for .NET Introduction&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Back to the previous post; &lt;a title="Rx Part 7 – Hot and Cold Observables" href="http://leecampbell.blogspot.com/2010/08/rx-part-7-hot-and-cold-observables.html"&gt;Rx Part 7 – Hot and Cold Observables&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Forward to next post; &lt;a href="http://leecampbell.blogspot.com/2011/03/rx-part-9join-window-buffer-and-group.html"&gt;Part 9 – Join, Window, Buffer and Group Join&lt;/a&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:29ce7b1c-0f37-4531-be9c-bac237e93013" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-3226080342334616352?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/3226080342334616352/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=3226080342334616352' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/3226080342334616352'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/3226080342334616352'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/10/rx-part-8-testing-rx.html' title='Rx Part 8 - Testing Rx'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-887283992955455731</id><published>2010-08-24T17:38:00.002+01:00</published><updated>2011-07-02T09:24:15.821+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Reactive Extensions for .NET an Introduction</title><content type='html'>Welcome to my series introducing &lt;a title="Reactive Extensions to .NET" href="http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx" target="_blank"&gt;Reactive Extensions to .NET&lt;/a&gt; (Rx). This series is aimed at any .NET developer curious about the IObservable&amp;lt;T&amp;gt;&lt;t&gt; and IObserver&amp;lt;T&amp;gt;&lt;t&gt; interfaces that have popped up in .NET 4. However Rx is a library so, &lt;strike&gt;Silverlight 3&lt;/strike&gt; &amp;amp; Silverlight 4 developers as well as .NET 3.5, Windows Phone and JavaScript coders can download the library. Rx is big. It is big in allsorts of ways:   &lt;ol&gt;   &lt;li&gt;In the way that it tackles the Observer pattern is bold &lt;/li&gt;    &lt;li&gt;In the way it tackles concurrency is quite a shift from how I have done it before. &lt;/li&gt;    &lt;li&gt;The number of (extension) methods is huge. &lt;/li&gt;    &lt;li&gt;The way in which it integrates with LINQ to leverage LINQ's composability &amp;amp; declarative style &lt;/li&gt;    &lt;li&gt;The fact that any .NET developer should care. UI developer, backend algorithm coder or integrator; It helps all of us. &lt;/li&gt;    &lt;li&gt;The future plans are even more grand, but that is a different series all together :-) &lt;/li&gt; &lt;/ol&gt; In this series I will introduce you to:   &lt;ul&gt;   &lt;li&gt;the new types the Rx will provide &lt;/li&gt;    &lt;li&gt;the extension methods and how to use them &lt;/li&gt;    &lt;li&gt;how to manage subscriptions to &amp;quot;streams&amp;quot; of data &lt;/li&gt;    &lt;li&gt;how to deal with concurrency to your advantage and avoid the common old pitfalls &lt;/li&gt;    &lt;li&gt;how to compose, aggregate and transform streams &lt;/li&gt;    &lt;li&gt;how to build workflows with Rx &lt;/li&gt;    &lt;li&gt;some tips and tricks I have picked while using Rx over the past months. &lt;/li&gt; &lt;/ul&gt; So &lt;a title="Reactive Extensions to .NET" href="http://msdn.microsoft.com/en-us/data/gg577609" target="_blank"&gt;download the assemblies&lt;/a&gt; to reference, fire up Visual Studio and let's get started:   &lt;ul&gt;   &lt;li&gt;&lt;a title="Part 1 - Introduction to Rx" href="http://leecampbell.blogspot.com/2010/05/intro-to-rx.html"&gt;Part 1 - Introduction to Rx&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a title="Part 2 - Static and extension methods" href="http://leecampbell.blogspot.com/2010/05/rx-part-2-static-and-extension-methods.html"&gt;Part 2 - Static and extension methods&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a title="Part 3 - Lifetime management – Completing and Unsubscribing" href="http://leecampbell.blogspot.com/2010/05/rx-part-3-lifetime-management.html"&gt;Part 3 - Lifetime management – Completing and Unsubscribing&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a title="Part 4 - Flow control" href="http://leecampbell.blogspot.com/2010/05/rx-part-4-flow-control.html"&gt;Part 4 - Flow control&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a title="Part 5 - Combining multiple IObservable streams" href="http://leecampbell.blogspot.com/2010/06/rx-part-5-combining-multiple.html"&gt;Part 5 - Combining multiple IObservable streams&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a title="Part 6 - Scheduling and threading" href="http://leecampbell.blogspot.com/2010/06/rx-part-6-scheduling-and-threading.html"&gt;Part 6 - Scheduling and threading&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a title="Part 7 - Hot and Cold observables" href="http://leecampbell.blogspot.com/2010/08/rx-part-7-hot-and-cold-observables.html"&gt;Part 7 - Hot and Cold observables&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a title="Part 8 - Testing Rx" href="http://leecampbell.blogspot.com/2010/10/rx-part-8-testing-rx.html" target="_blank"&gt;Part 8 – Testing Rx&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a title="Part 9 – Join, Window, Buffer and Group Join" href="http://leecampbell.blogspot.com/2011/03/rx-part-9join-window-buffer-and-group.html"&gt;Part 9 – Join, Window, Buffer and Group Join&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The full source code is now available either via SVN at &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or as a &lt;a title="Introduction to Rx code samples." href="http://rx-samples.googlecode.com/files/rx-samples_v009.zip"&gt;zip file&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Edit – This series of posts was first created in mid 2010. The Rx framework has gone through numerous changes during and after the writing of these posts. I am constantly making an effort to ensure that the blog stays as current as I can make it –Lee Campbell&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:dc70c31a-ef69-4d99-9d16-8db5bd751782" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-887283992955455731?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/887283992955455731/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=887283992955455731' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/887283992955455731'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/887283992955455731'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html' title='Reactive Extensions for .NET an Introduction'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-7238653685203103473</id><published>2010-08-19T12:31:00.001+01:00</published><updated>2011-03-14T07:59:26.328Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Rx Part 7 – Hot and Cold Observables</title><content type='html'>&lt;p&gt;In this post we will look how to describe and handle 2 styles of observable streams &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Streams that are passive and start publishing on request, &lt;/li&gt;    &lt;li&gt;Streams that are active and publish regardless of subscriptions. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;In this sense passive streams are called &lt;em&gt;Cold&lt;/em&gt; and active are described as being &lt;em&gt;Hot&lt;/em&gt;. You can draw some similarities between implementations of the IObservable&amp;lt;T&amp;gt; interface and implementations of the IEnumerable&amp;lt;T&amp;gt; interface with regards to Hot and Cold. With IEnumerable&amp;lt;T&amp;gt; you could have an “On demand” collection via the yield return syntax, or you could have an eager evaluation by populating a List&amp;lt;T&amp;gt;, for example, and returning that (as per the example below)&lt;/p&gt;  &lt;pre class="csharpcode"&gt;Do(LazyEvaluation());
Do(EagerEvaluation());


&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Do(IEnumerable&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; list)
{
  &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var i &lt;span class="kwrd"&gt;in&lt;/span&gt; list)
  {
    Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Read out first value of {0}&amp;quot;&lt;/span&gt;, i);
    &lt;span class="kwrd"&gt;break&lt;/span&gt;;
  }
}

&lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; LazyEvaluation()
{
  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;About to return 1&amp;quot;&lt;/span&gt;);
  &lt;span class="kwrd"&gt;yield&lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; 1;
  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;About to return 2&amp;quot;&lt;/span&gt;);&lt;span class="rem"&gt;//Never called in this example&lt;/span&gt;
  &lt;span class="kwrd"&gt;yield&lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; 2;
}

&lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; EagerEvaluation()
{
  var result = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();
  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;About to return 1&amp;quot;&lt;/span&gt;);
  result.Add(1);
  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;About to return 2&amp;quot;&lt;/span&gt;);&lt;span class="rem"&gt;//executed but not used.&lt;/span&gt;
  result.Add(2);
  &lt;span class="kwrd"&gt;return&lt;/span&gt; result;
}&lt;/pre&gt;

&lt;p&gt;Implementations of IObservable&amp;lt;T&amp;gt; can exhibit similar variations in style.&lt;/p&gt;

&lt;p&gt;Examples of Hot observables that could publish regardless of if there are any subscribers would be:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Mouse movements &lt;/li&gt;

  &lt;li&gt;Timer events &lt;/li&gt;

  &lt;li&gt;broadcasts like ESB channels or UDP network packets. &lt;/li&gt;

  &lt;li&gt;price ticks from a trading exchange &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Some examples of Cold observables would be:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;subscription to a queue &lt;/li&gt;

  &lt;li&gt;when Rx is used for an asynchronous request &lt;/li&gt;

  &lt;li&gt;on demand streams &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this post we will look at 3 scenarios in which cold, hot and both cold &amp;amp; hot are implemented.&lt;/p&gt;

&lt;h4&gt;Cold Observables&lt;/h4&gt;

&lt;p&gt;In this first example we have a requirement to fetch a list of products from a service. In our implementation we choose to return an IObservable&amp;lt;string&amp;gt; and as we get the results we publish them until we have the full list and then we publish an OnComplete. This is a pretty simple example.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IObservable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; GetProducts()
{
  &lt;span class="kwrd"&gt;return&lt;/span&gt; Observable.CreateWithDisposable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;(
    o =&amp;gt;
    {
      &lt;span class="kwrd"&gt;using&lt;/span&gt;(var conn = &lt;span class="kwrd"&gt;new&lt;/span&gt; SqlConnection(&lt;span class="str"&gt;@&amp;quot;Data Source=.\SQLSERVER;Initial Catalog=AdventureWorksLT2008;Integrated Security=SSPI;&amp;quot;&lt;/span&gt;))
      &lt;span class="kwrd"&gt;using&lt;/span&gt; (var cmd = &lt;span class="kwrd"&gt;new&lt;/span&gt; SqlCommand(&lt;span class="str"&gt;&amp;quot;Select Name FROM SalesLT.ProductModel&amp;quot;&lt;/span&gt;, conn))
      {
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        &lt;span class="kwrd"&gt;while&lt;/span&gt; (reader.Read())
        {
          o.OnNext(reader.GetString(0));
        }
        o.OnCompleted();
        &lt;span class="kwrd"&gt;return&lt;/span&gt; Disposable.Create(()=&amp;gt;Console.WriteLine(&lt;span class="str"&gt;&amp;quot;--Disposed--&amp;quot;&lt;/span&gt;));
      }
    });
}&lt;/pre&gt;

&lt;p&gt;This style of API would allow for a non blocking call to fetch the list of products and would inform the consumer of when the list was complete. This is fairly common stuff, but note that every time this is called, the database will be accessed again. &lt;/p&gt;

&lt;p&gt;In the example above I use Disposable.Create factory method. This factory method just creates an implementation of IDisposable that executes a given action when disposed. This is perfect for doing a Console.WriteLine once the subscription has been disposed.&lt;/p&gt;

&lt;p&gt;In this example below, we have a consumer of our above code, but it explicitly only wants up to 3 values (the full set has 128 values). This code illustrates that the Take(3) expression will restrict what the consumer receives but GetProducts() method will still publish all of the values.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ColdSample()
{
  var productStream = GetProducts().Take(3);
  productStream.Subscribe(Console.WriteLine);
  Console.ReadLine();
}&lt;/pre&gt;

&lt;h4&gt;Hot Observables&lt;/h4&gt;

&lt;p&gt;Trying to come up with an example for Hot Observables has been a real pain. I have started off with examples with some sort of context (streaming stock prices or weather information) but this all seemed to detract from the real working of the code. So I think it is best to step through this slowly with a contrived demo and build it up to a piece of code you might actually want to use.&lt;/p&gt;

&lt;p&gt;Let us start with subscribing to an Interval. In the example below we subscribe to the same Observable that is created via the Interval extension method. The delay between the two subscriptions should demonstrate that while they are subscribed to the same observable instance, it is not the same logical stream of data.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SimpleColdSample()
{
  var period = TimeSpan.FromSeconds(1);
  var observable = Observable.Interval(period);
  observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;first subscription : {0}&amp;quot;&lt;/span&gt;, i));
  Thread.Sleep(period);
  observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;second subscription : {0}&amp;quot;&lt;/span&gt;, i));
  Console.ReadKey();
  &lt;span class="rem"&gt;/* Ouput:&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 0&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   second subscription : 0&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 2&lt;/span&gt;
&lt;span class="rem"&gt;   second subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 3&lt;/span&gt;
&lt;span class="rem"&gt;   second subscription : 2   &lt;/span&gt;
&lt;span class="rem"&gt;   */&lt;/span&gt;
}&lt;/pre&gt;

&lt;h5&gt;Publish and Connect&lt;/h5&gt;

&lt;p&gt;If I want to be able to share the actual stream of data and not just the instance of the observable, I can use the Publish() extension method. This will return an IConnectableObservable&amp;lt;T&amp;gt;, which extends IObservable&amp;lt;T&amp;gt; by adding the single Connect() method. By using the Publish() then the Connect() method, we can get this functionality.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SimpleConnectSample()
{
  var period = TimeSpan.FromSeconds(1);
  var observable = Observable.Interval(period).Publish();
  observable.Connect();
  observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;first subscription : {0}&amp;quot;&lt;/span&gt;, i));
  Thread.Sleep(period);
  observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;second subscription : {0}&amp;quot;&lt;/span&gt;, i));
  Console.ReadKey();
  &lt;span class="rem"&gt;/* Ouput:&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 0&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   second subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 2&lt;/span&gt;
&lt;span class="rem"&gt;   second subscription : 2   &lt;/span&gt;
&lt;span class="rem"&gt;   */&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;In the example above the &lt;em&gt;observable&lt;/em&gt; variable is an IConnectableObservable&amp;lt;T&amp;gt;, and by calling Connect() it will subscribe to the underlying (the Observable.Interval). In this case we are quick enough to subscribe before the first item is published but only on the first subscription. The second subscription subscribes late and misses the first publication. We could move the invocation of the Connect() method until after each of the subscriptions have been made so that even with the Thread.Sleep we wont really subscribe to the underlying until after both subscriptions are made. This would be done as follows:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SimpleConnectSample()
{
  var period = TimeSpan.FromSeconds(1);
  var observable = Observable.Interval(period).Publish();
  observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;first subscription : {0}&amp;quot;&lt;/span&gt;, i));
  Thread.Sleep(period);
  observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;second subscription : {0}&amp;quot;&lt;/span&gt;, i));
  observable.Connect();
  Console.ReadKey();
  &lt;span class="rem"&gt;/* Ouput:&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 0&lt;/span&gt;
&lt;span class="rem"&gt;   second subscription : 0&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   second subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 2&lt;/span&gt;
&lt;span class="rem"&gt;   second subscription : 2   &lt;/span&gt;
&lt;span class="rem"&gt;   */&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;You can probably imagine how this could be quite useful where an application had the need to share streams of data. In a trading application if you wanted to consume a price stream for a certain asset in more than one place, you would want to reuse that stream and not have to make another subscription to the server providing that data. Publish() and Connect() are perfect solutions for this. &lt;/p&gt;

&lt;h5&gt;Disposal of connections and subscriptions&lt;/h5&gt;

&lt;p&gt;What does become interesting is how disposal is performed. What was not covered above is that the Connect() method returns an IDisposable. By disposing of the “connection” you can turn the stream on and off (Connect() to turn it on and then disposing of the connection to turn it off). In this example we see that the the stream can be connected and disconnected multiple times.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ConnectAndDisposeSample()
{
  var period = TimeSpan.FromSeconds(1);
  var observable = Observable.Interval(period).Publish();
  observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;subscription : {0}&amp;quot;&lt;/span&gt;, i));
  var exit = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
  &lt;span class="kwrd"&gt;while&lt;/span&gt; (!exit)
  {
    Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Press enter to connect, esc to exit.&amp;quot;&lt;/span&gt;);
    var key = Console.ReadKey(&lt;span class="kwrd"&gt;true&lt;/span&gt;);
    &lt;span class="kwrd"&gt;if&lt;/span&gt;(key.Key== ConsoleKey.Enter)
    {
      var connection = observable.Connect();  &lt;span class="rem"&gt;//--Connects here--&lt;/span&gt;
      Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Press any key to dispose of connection.&amp;quot;&lt;/span&gt;);
      Console.ReadKey();
      connection.Dispose();                   &lt;span class="rem"&gt;//--Disconnects here--&lt;/span&gt;
    }
    &lt;span class="kwrd"&gt;if&lt;/span&gt;(key.Key==ConsoleKey.Escape)
    {
      exit = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
    }
  }
  &lt;span class="rem"&gt;/* Ouput:&lt;/span&gt;
&lt;span class="rem"&gt;   Press enter to connect, esc to exit.&lt;/span&gt;
&lt;span class="rem"&gt;   Press any key to dispose of connection.&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 0&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 2&lt;/span&gt;
&lt;span class="rem"&gt;   Press enter to connect, esc to exit.&lt;/span&gt;
&lt;span class="rem"&gt;   Press any key to dispose of connection.&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 0&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 2&lt;/span&gt;
&lt;span class="rem"&gt;   Press enter to connect, esc to exit.   &lt;/span&gt;
&lt;span class="rem"&gt;   */&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;Let us finally consider automatic disposal of a connection. It would be common place for a single stream to be shared between subscriptions, as per the price stream example mentioned above. It would however also be common place for the developer to want to only have the stream running hot if there are subscriptions to it. Therefore it seems not only obvious that there should be a mechanism for automatically connecting (once a subscription has been made), but also a mechanism for disconnecting (once there are no more subscriptions) from a stream. First let us look at what happens to a stream when we connect with no subscribers, and then later unsubscribe:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; OrphanedStreamExample()
{
  var period = TimeSpan.FromSeconds(1);
  var observable = Observable.Interval(period)
    .Do(l =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Publishing {0}&amp;quot;&lt;/span&gt;, l)) &lt;span class="rem"&gt;//produce Side effect to show it is running.&lt;/span&gt;
    .Publish();
  observable.Connect();
  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Press any key to subscribe&amp;quot;&lt;/span&gt;);
  Console.ReadKey();
  var subscription = observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;subscription : {0}&amp;quot;&lt;/span&gt;, i));

  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Press any key to unsubscribe.&amp;quot;&lt;/span&gt;);
  Console.ReadKey();
  subscription.Dispose();

  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Press any key to exit.&amp;quot;&lt;/span&gt;);
  Console.ReadKey();
  &lt;span class="rem"&gt;/* Ouput:&lt;/span&gt;
&lt;span class="rem"&gt;   Press any key to subscribe&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 0&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 1&lt;/span&gt;
&lt;span class="rem"&gt;   Press any key to unsubscribe.&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 2&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 2&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 3&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 3&lt;/span&gt;
&lt;span class="rem"&gt;   Press any key to exit.&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 4&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 5&lt;/span&gt;
&lt;span class="rem"&gt;   */&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;A few things to note here:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;I use the &lt;em&gt;Do&lt;/em&gt; extension method to create side effects on the stream (ie writing to the console). This allows us to see when the stream is actually connected. &lt;/li&gt;

  &lt;li&gt;We connect first and then subscribe, which means we can be publishing without any subscriptions. &lt;/li&gt;

  &lt;li&gt;We dispose of our subscription but don’t dispose of the connection which means the stream will still be running. This means we will be publishing even though there are no subscriptions. &lt;/li&gt;
&lt;/ol&gt;

&lt;h5&gt;RefCount&lt;/h5&gt;

&lt;p&gt;Taking the last example, if we just comment out the line that makes the Connection, and then add a further extension method to our creation of our observable RefCount we have magically implemented all of our requirements. RefCount will take an IConnectableObservable&amp;lt;T&amp;gt; and turn it back into an IObservable&amp;lt;T&amp;gt; and automatically implement the connect and disconnect behaviour we are looking for.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; RefCountExample()
{
  var period = TimeSpan.FromSeconds(1);
  var observable = Observable.Interval(period)
    .Do(l =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Publishing {0}&amp;quot;&lt;/span&gt;, l)) &lt;span class="rem"&gt;//produce Side effect to show it is running.&lt;/span&gt;
    .Publish()
    .RefCount();
  &lt;span class="rem"&gt;//observable.Connect(); Use RefCount instead now&lt;/span&gt;
  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Press any key to subscribe&amp;quot;&lt;/span&gt;);
  Console.ReadKey();
  var subscription = observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;subscription : {0}&amp;quot;&lt;/span&gt;, i));

  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Press any key to unsubscribe.&amp;quot;&lt;/span&gt;);
  Console.ReadKey();
  subscription.Dispose();

  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Press any key to exit.&amp;quot;&lt;/span&gt;);
  Console.ReadKey();
  &lt;span class="rem"&gt;/* Ouput:&lt;/span&gt;
&lt;span class="rem"&gt;   Press any key to subscribe&lt;/span&gt;
&lt;span class="rem"&gt;   Press any key to unsubscribe.&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 0&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 0&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 1&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 2&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 2&lt;/span&gt;
&lt;span class="rem"&gt;   Press any key to exit.&lt;/span&gt;
&lt;span class="rem"&gt;   */&lt;/span&gt;
}&lt;/pre&gt;

&lt;h4&gt;Other Connectable Observables&lt;/h4&gt;

&lt;p&gt;While this is a post about Hot and Cold Observables, I think it is worth mentioning the other ways IConnectableObservable&amp;lt;T&amp;gt; can pop up.&lt;/p&gt;

&lt;h5&gt;Prune&lt;/h5&gt;

&lt;p&gt;The prune method is effectively a non blocking .Last() call. You can consider it similar to an AsyncSubject&amp;lt;T&amp;gt; wrapping your target Observable so that you get equivalent semantics of only returning the last value of an observable and only once it completes. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; PruneExample()
{
  var period = TimeSpan.FromSeconds(1);
  var observable = Observable.Interval(period)
    .Take(5)
    .Do(l =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Publishing {0}&amp;quot;&lt;/span&gt;, l)) &lt;span class="rem"&gt;//produce Side effect to show it is running.&lt;/span&gt;
    .Prune();
  observable.Connect();
  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Press any key to subscribe&amp;quot;&lt;/span&gt;);
  Console.ReadKey();
  var subscription = observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;subscription : {0}&amp;quot;&lt;/span&gt;, i));

  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Press any key to unsubscribe.&amp;quot;&lt;/span&gt;);
  Console.ReadKey();
  subscription.Dispose();

  Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Press any key to exit.&amp;quot;&lt;/span&gt;);
  Console.ReadKey();
  &lt;span class="rem"&gt;/* Ouput:&lt;/span&gt;
&lt;span class="rem"&gt;   Press any key to subscribe&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 0&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 1&lt;/span&gt;
&lt;span class="rem"&gt;   Press any key to unsubscribe.&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 2&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 3&lt;/span&gt;
&lt;span class="rem"&gt;   Publishing 4&lt;/span&gt;
&lt;span class="rem"&gt;   subscription : 4&lt;/span&gt;
&lt;span class="rem"&gt;   Press any key to exit.&lt;/span&gt;
&lt;span class="rem"&gt;   */&lt;/span&gt;
}&lt;/pre&gt;

&lt;h5&gt;Replay &lt;/h5&gt;

&lt;p&gt;The Replay extension method allows you take an existing Observable and give it “replay” semantics as per the ReplaySubject&amp;lt;T&amp;gt;. As a reminder, the ReplaySubject&amp;lt;T&amp;gt; will cache all values so that any late subscribers will also get all of the values. In this example 2 subscriptions are made on time, and then a third subscription can be made after they complete. Even though the third subscription can be done after the OnComplete we can still get all of the values.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ReplayOnHotExample()
{
  var period = TimeSpan.FromSeconds(1);
  var hot = Observable.Interval(period)
    .Take(3)
    .Publish();
  hot.Connect();
  Thread.Sleep(period); &lt;span class="rem"&gt;//Run hot and ensure a value is lost.&lt;/span&gt;
  var observable = hot.Replay();
  observable.Connect();
  observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;first subscription : {0}&amp;quot;&lt;/span&gt;, i));
  Thread.Sleep(period);
  observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;second subscription : {0}&amp;quot;&lt;/span&gt;, i));

  Console.ReadKey();
  observable.Subscribe(i =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;third subscription : {0}&amp;quot;&lt;/span&gt;, i));
  Console.ReadKey();

  &lt;span class="rem"&gt;/* Ouput:&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   second subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   first subscription : 2&lt;/span&gt;
&lt;span class="rem"&gt;   second subscription : 2   &lt;/span&gt;
&lt;span class="rem"&gt;   third subscription : 1&lt;/span&gt;
&lt;span class="rem"&gt;   third subscription : 2&lt;/span&gt;
&lt;span class="rem"&gt;   */&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;I hope that gives some insight to &lt;em&gt;Hot&lt;/em&gt; and &lt;em&gt;Cold&lt;/em&gt; observables. I think this is one of the more mysterious parts of Rx for many newbies so I hope that it helps clear up some of the cool stuff you can do with Rx. I sure many of you will look forward to finding ways to implement this in your next application.&lt;/p&gt;

&lt;p&gt;For more information on IConnectableObservable&amp;lt;T&amp;gt; and Hot/Cold streams check out these resources:&lt;/p&gt;

&lt;p&gt;&lt;a title="Rx API in depth Hot and Cold Observables on channel9.msdn.com" href="http://channel9.msdn.com/posts/J.Van.Gogh/Rx-API-in-depth-Hot-and-Cold-observables/" target="_blank"&gt;channel 9 video on Hot and Cold observables&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a title="RX for beginners -Part 9 hot vs cold observable" href="http://blogs.microsoft.co.il/blogs/bnaya/archive/2010/03/13/rx-for-beginners-part-9-hot-vs-cold-observable.aspx" target="_blank"&gt;Hot and Cold by Bnaya Eshet&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The full source code is now available either via svn at &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or as a &lt;a title="rx-samples source code" href="http://rx-samples.googlecode.com/files/rx-samples_v009.zip" target="_blank"&gt;zip file&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Back to the &lt;a title="Reactive Extensions for .NET Introduction - Lee Campbell" href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;contents&lt;/a&gt; page for &lt;a title="Reactive Extensions for .NET Introduction - Lee Campbell" href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions for .NET Introduction&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Back to the previous post; &lt;a href="http://leecampbell.blogspot.com/2010/06/rx-part-6-scheduling-and-threading.html"&gt;Part 6 - Scheduling and threading&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Forward to next post; &lt;a href="http://leecampbell.blogspot.com/2010/10/rx-part-8-testing-rx.html"&gt;Part 8 – Testing Rx&lt;/a&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:a717e7ae-9dec-4a1d-bc6c-446c0b3cde6f" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-7238653685203103473?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/7238653685203103473/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=7238653685203103473' title='8 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7238653685203103473'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7238653685203103473'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/08/rx-part-7-hot-and-cold-observables.html' title='Rx Part 7 – Hot and Cold Observables'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>8</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-966330026506466762</id><published>2010-06-27T23:08:00.003+01:00</published><updated>2011-03-14T07:58:57.196Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='Concurrency'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Rx Part 6 – Scheduling and Threading</title><content type='html'> So far in the series of posts we have managed to avoid any explicit usage of threading or concurrency. There are some methods that we have covered that implicitly will be introducing some level of concurrency to perform their jobs (e.g. : &lt;em&gt;Buffer&lt;/em&gt;, &lt;em&gt;Delay&lt;/em&gt;, &lt;em&gt;Sample&lt;/em&gt; etc all require a separate thread to do their magic). However most of this has been kindly abstracted away from us. This post will look at the beauty of the Rx API and its ability to effectively remove the need for WaitHandles, and any explicit calls to using &lt;em&gt;Thread&lt;/em&gt;s, the &lt;em&gt;ThreadPool&lt;/em&gt; and the new shiny &lt;em&gt;Task&lt;/em&gt; type.    &lt;p&gt;A friend of mine once wisely stated that you should always understand at least one layer below what you are coding. At the time he was referring to networking protocols, but I think it is sage advice for all programming. On the current project I am working on there are some very savvy developers that are very comfortable working in a multithreaded environment. The project has client and server side threading problems that we have had to tackle. I believe the whole team would agree that it has bee amazing that amount of concurrency that Rx will handle for you in a declarative way. The code base is virtually free of &lt;em&gt;WaitHandle&lt;/em&gt;s, &lt;em&gt;Monitor&lt;/em&gt; or &lt;em&gt;lock&lt;/em&gt; usage, or any explicit creation of threads. This has evolved into this state over time as we have come to grips with the power of Rx and the end result is far cleaner code. However, having the experience on the team allowed us to find out ways we should and shouldn’t be using Rx which would have been just too hard for me to do alone.&lt;/p&gt;  &lt;p&gt;Getting back to my friend’s comment about understanding the underlying subsystem, this is especially important when dealing with Rx and scheduling. Just because Rx abstracts some of this away, it does not mean that you cant still create problems for yourself if you are not careful. Before I scare you too much let’s look at some of the Scheduling features of Rx.&lt;/p&gt;  &lt;h4&gt;Scheduling&lt;/h4&gt;  &lt;p&gt;In the Rx world, you can control the scheduling of two things&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;The invocation of the subscription &lt;/li&gt;    &lt;li&gt;The publishing of notifications &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;As you could probably guess these are exposed via two extension methods to IObservable&amp;lt;T&amp;gt; called &lt;em&gt;SubscribeOn&lt;/em&gt; and &lt;em&gt;ObserveOn&lt;/em&gt;. Both methods have an overload that take an IScheduler and will return an IObservable&amp;lt;T&amp;gt; so you can chain methods together.&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Observable
{
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IObservable&amp;lt;TSource&amp;gt; ObserveOn&amp;lt;TSource&amp;gt;(
      this IObservable&amp;lt;TSource&amp;gt; source, IScheduler scheduler) 
  {...}
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IObservable&amp;lt;TSource&amp;gt; SubscribeOn&amp;lt;TSource&amp;gt;(
      this IObservable&amp;lt;TSource&amp;gt; source, IScheduler scheduler) 
  {...}
}

&lt;span class="kwrd"&gt;public&lt;/span&gt; interface IScheduler
{
    IDisposable Schedule(&lt;span class="kwrd"&gt;Action&lt;/span&gt; &lt;span class="kwrd"&gt;action&lt;/span&gt;);
    IDisposable Schedule(&lt;span class="kwrd"&gt;Action&lt;/span&gt; &lt;span class="kwrd"&gt;action&lt;/span&gt;, TimeSpan dueTime);
    DateTimeOffset Now { &lt;span class="kwrd"&gt;get&lt;/span&gt;; }
}&lt;/pre&gt;

&lt;p&gt;The IScheduler interface is of less interest to me than the types that implement the interface. Depending on your platform* (Silverlight3, Silverlight4, .Net 3.5, .Net 4.0) you will be exposed appropriate implementations via a static class Scheduler. These are the static properties that you can find on the Scheduler type that expose different schedulers. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Scheduler.Dispatcher&lt;/strong&gt;&lt;/em&gt; will ensure that the actions are performed on the Dispatcher, which is obviously useful for Silverlight and WPF applications. You can imagine that the implementation for this would just delegate any calls to ISchedule(Action) straight to Dispatcher.BeginInvoke(Action)&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Scheduler.NewThread&lt;/strong&gt;&lt;/em&gt; will schedule all actions onto a new thread.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Scheduler.ThreadPool&lt;/strong&gt;&lt;/em&gt; will schedule all actions onto the Thread Pool.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Scheduler.TaskPool&lt;/strong&gt;&lt;/em&gt; (which is only available to Silverlight 4 and .NET 4.0) will schedule actions onto the TaskPool.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Scheduler.Immediate&lt;/strong&gt;&lt;/em&gt; will ensure the action is not scheduled but is executed immediately. &lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Scheduler.CurrentThread&lt;/strong&gt;&lt;/em&gt; just ensures that the actions are performed on the thread that made the original call. This is different to &lt;em&gt;Immediate&lt;/em&gt;, as &lt;em&gt;CurrentThread&lt;/em&gt; will queue the action to be performed. Note the difference in the output of the following code. One method passes &lt;em&gt;Scheduler.Immediate&lt;/em&gt;, the other passes &lt;em&gt;Scheduler.CurrentThread&lt;/em&gt;.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ScheduleTasks(IScheduler scheduler)
{
    Action leafAction = () =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;leafAction.&amp;quot;&lt;/span&gt;);
    Action innerAction = () =&amp;gt;
                             {
                                 Console.WriteLine(&lt;span class="str"&gt;&amp;quot;innerAction start.&amp;quot;&lt;/span&gt;);
                                 scheduler.Schedule(leafAction);
                                 Console.WriteLine(&lt;span class="str"&gt;&amp;quot;innerAction end.&amp;quot;&lt;/span&gt;);
                             };
    Action outerAction = () =&amp;gt;
                             {
                                 Console.WriteLine(&lt;span class="str"&gt;&amp;quot;outer start.&amp;quot;&lt;/span&gt;);
                                 scheduler.Schedule(innerAction);
                                 Console.WriteLine(&lt;span class="str"&gt;&amp;quot;outer end.&amp;quot;&lt;/span&gt;);
                             };
    scheduler.Schedule(outerAction);
}

&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; CurrentThreadExample()
{
    ScheduleTasks(Scheduler.CurrentThread);
    Console.ReadLine();
    &lt;span class="rem"&gt;/*Output:&lt;/span&gt;
&lt;span class="rem"&gt;     * outer start.&lt;/span&gt;
&lt;span class="rem"&gt;     * outer end.&lt;/span&gt;
&lt;span class="rem"&gt;     * innerAction start.&lt;/span&gt;
&lt;span class="rem"&gt;     * innerAction end.&lt;/span&gt;
&lt;span class="rem"&gt;     * leafAction.&lt;/span&gt;
&lt;span class="rem"&gt;     */&lt;/span&gt;
}

&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; ImmediateExample()
{
    ScheduleTasks(Scheduler.Immediate);
    Console.ReadLine();
    &lt;span class="rem"&gt;/*Output:&lt;/span&gt;
&lt;span class="rem"&gt;     * outer start.&lt;/span&gt;
&lt;span class="rem"&gt;     * innerAction start.&lt;/span&gt;
&lt;span class="rem"&gt;     * leafAction.&lt;/span&gt;
&lt;span class="rem"&gt;     * innerAction end.&lt;/span&gt;
&lt;span class="rem"&gt;     * outer end.&lt;/span&gt;
&lt;span class="rem"&gt;     */&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;*Sorry Rx for JavaScript, I have not even opened the box on you and don’t know anything about scheduling in JavaScript.&lt;/p&gt;

&lt;h5&gt;Examples&lt;/h5&gt;

&lt;p&gt;So they are each of our Schedulers, lets see some of them in use. The think I want to point out here is that the first few times I used these overloads I had them confused as to what they actually did. You should use the SubscribeOn method to describe how you want any warm up and background processing code to be scheduled. ObserveOn method is used to describe where you want your notification scheduled to. So for example, if you had a WPF application that used Rx to populate and ObservableCollection&amp;lt;T&amp;gt; then you would almost certainly want to use SubscribeOn with one of the Threaded schedulers (NewThread, ThreadPool or maybe TaskPool) and then you would have to use the Dispatcher scheduler to update your collection. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; LoadCustomers()
{
    _customerService.GetCustomers()
        .SubscribeOn(Scheduler.NewThread)
        .ObserveOn(Scheduler.Dispatcher)
        .Subscribe(Customers.Add);
}&lt;/pre&gt;

&lt;p&gt;So all of the schedulers just offer a nice abstraction to us to utilise the various ways we can write concurrent code. Besides saving me from having to write the tedious code to get code onto a new thread or thread pool it also makes Rx threading easy. Oh Rx, you thought I had forgotten. I didn’t think that any of the schedulers except Current &amp;amp; Immediate warranted a further explanation but, I do think it is worth pointing out some of the “fun” threading problems you can face even though the scheduling has been abstracted away from you.&lt;/p&gt;

&lt;h4&gt;Deadlocks&lt;/h4&gt;

&lt;p&gt;When writing the current application my team is working on we found out the hard way that Rx code can most certainly deadlock. When you consider that some calls (like .First() ) are blocking, and that we can schedule work to be done in the future, it becomes obvious that race condition can apply. This example is the most simple deadlock I could think of. It is fairly silly but it will get the ball rolling.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var stream = &lt;span class="kwrd"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();
Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Next line should deadlock the system.&amp;quot;&lt;/span&gt;);
var &lt;span class="kwrd"&gt;value&lt;/span&gt; = stream.First();
stream.OnNext(1);
Console.WriteLine(&lt;span class="str"&gt;&amp;quot;I can never execute....&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

&lt;p&gt;Hopefully we wont ever write code that silly, and if we did our tests would give us fairly quick feed back that things were wrong. What lets deadlocks slip into the system is when they manifest themselves at integration points. This example may be a little harder to find but is only small step away from the silly 1st example. Here we block in the constructor on a UI element which will always be created on the dispatcher. The blocking call is waiting for an event, that can only be raised from the dispatcher – deadlock.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; Window1()
{
    InitializeComponent();
    DataContext = &lt;span class="kwrd"&gt;this&lt;/span&gt;;
    Value = &lt;span class="str"&gt;&amp;quot;Default value&amp;quot;&lt;/span&gt;;

    &lt;span class="rem"&gt;//Deadlock! We need the dispatcher to continue&lt;/span&gt;
    &lt;span class="rem"&gt;// to allow me to click the button to produce a value.&lt;/span&gt;
    Value = _subject.First(); 

    &lt;span class="rem"&gt;//This will give same result but will not be blocking(deadlocking).&lt;/span&gt;
    _subject.Take(1).Subscribe(&lt;span class="kwrd"&gt;value&lt;/span&gt; =&amp;gt; Value = &lt;span class="kwrd"&gt;value&lt;/span&gt;);
}

&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; MyButton_Click(&lt;span class="kwrd"&gt;object&lt;/span&gt; sender, RoutedEventArgs e)
{
    _subject.OnNext(&lt;span class="str"&gt;&amp;quot;New Value&amp;quot;&lt;/span&gt;);
}

&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Value
{
    get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _value; }
    set
    {
        _value = &lt;span class="kwrd"&gt;value&lt;/span&gt;;
        var handler = PropertyChanged;
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (handler != &lt;span class="kwrd"&gt;null&lt;/span&gt;) handler(&lt;span class="kwrd"&gt;this&lt;/span&gt;, &lt;span class="kwrd"&gt;new&lt;/span&gt; PropertyChangedEventArgs(&lt;span class="str"&gt;&amp;quot;Value&amp;quot;&lt;/span&gt;));
    }
}&lt;/pre&gt;

&lt;p&gt;In this example we start seeing things that can become more sinister. This example has a Button that the click command will try to get the first value from an Observable exposed via an interface.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;partial&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Window1 : INotifyPropertyChanged
{
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; IMyService _service = &lt;span class="kwrd"&gt;new&lt;/span&gt; MyService(); &lt;span class="rem"&gt;//Imagine DI here.&lt;/span&gt;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; _value2;

    &lt;span class="kwrd"&gt;public&lt;/span&gt; Window1()
    {
        InitializeComponent();
        DataContext = &lt;span class="kwrd"&gt;this&lt;/span&gt;;
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Value2
    {
        get { &lt;span class="kwrd"&gt;return&lt;/span&gt; _value2; }
        set
        {
            _value2 = &lt;span class="kwrd"&gt;value&lt;/span&gt;;
            var handler = PropertyChanged;
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (handler != &lt;span class="kwrd"&gt;null&lt;/span&gt;) handler(&lt;span class="kwrd"&gt;this&lt;/span&gt;, &lt;span class="kwrd"&gt;new&lt;/span&gt; PropertyChangedEventArgs(&lt;span class="str"&gt;&amp;quot;Value2&amp;quot;&lt;/span&gt;));
        }
    }

    &lt;span class="preproc"&gt;#region&lt;/span&gt; INotifyPropertyChanged Members

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;event&lt;/span&gt; PropertyChangedEventHandler PropertyChanged;

    &lt;span class="preproc"&gt;#endregion&lt;/span&gt;

    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; MyButton2_Click(&lt;span class="kwrd"&gt;object&lt;/span&gt; sender, RoutedEventArgs e)
    {
        Value2 = _service.GetTemperature().First();
    }
}&lt;/pre&gt;

&lt;p&gt;There is only a small problem here in that we block on the Dispatcher thread (.First() is a blocking call), however this manifest's itself into a deadlock if the service code is written incorrectly.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; MyService : IMyService
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; IObservable&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; GetTemperature()
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; Observable.Create&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;(
            o =&amp;gt;
                {
                    o.OnNext(27);
                    o.OnNext(26);
                    o.OnNext(24);
                    &lt;span class="kwrd"&gt;return&lt;/span&gt; () =&amp;gt; { };
                })
            .SubscribeOnDispatcher();
    }
}&lt;/pre&gt;

&lt;p&gt;This odd implementation with explicit scheduling will cause the 3 OnNext calls to be scheduled once the .First() call has finished, which is waiting for an OnNext to be called – Deadlock.&lt;/p&gt;

&lt;p&gt;So far this post has been a bit doom and gloom about scheduling and the problems you could face, that is not the intent. I just wanted to make it obvious that Rx was not going to solve the age old concurrency problems, but it will make it easier to get it right if you follow this simple rule.&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Only the final subscriber should be setting the scheduling. &lt;/li&gt;

  &lt;li&gt;Avoid using .First() &lt;em&gt;–Ed: that is for you Olivier. We will cal this rule 1b&lt;/em&gt; &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Where the last example came unstuck is that the service was dictating the scheduling paradigm when really it had no business doing so. Before we had a clear idea of where we should be doing the scheduling in my current project, we had allsorts of layers adding “helpful” scheduling code. What it ended up creating was a threading nightmare. When we removed all scheduling code and then located it in a single layer (at least in the Silverlight client) most of our concurrency problems went away. I recommend you do the same. At least in WPF/Silverlight applications, the pattern should be simple: “Subscribe on a Background thread; Observe on the Dispatcher”. &lt;/p&gt;

&lt;p&gt;So my challenge to the readers is to add to the comments:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Any other scheduling rules (2 seems quite small, and I was only going to have 1) &lt;/li&gt;

  &lt;li&gt;Post some nasty Rx race condition code &lt;/li&gt;

  &lt;li&gt;What rules do you have for Subscribing on the background thread? Which Scheduler should I use and when i.e. NewThread, ThreadPool &amp;amp; TaskPool. – and I come full circle about understanding one layer below that to which you are working. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Further reading/watching:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;This channel9 video has more interesting stuff including testing with schedulers &lt;a href="http://channel9.msdn.com/shows/Going+Deep/Wes-Dyer-and-Jeffrey-Van-Gogh-Inside-Rx-Virtual-Time/"&gt;http://channel9.msdn.com/shows/Going+Deep/Wes-Dyer-and-Jeffrey-Van-Gogh-Inside-Rx-Virtual-Time/&lt;/a&gt; &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The full source code is now available either via svn at &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or as a &lt;a href="http://rx-samples.googlecode.com/files/rx-samples_v008.zip"&gt;zip file&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Back to the &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;contents&lt;/a&gt; page for &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions for .NET Introduction&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Back to the previous post; &lt;a href="http://leecampbell.blogspot.com/2010/06/rx-part-5-combining-multiple.html"&gt;Part 5 - Combining multiple IObservable streams&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Forward to next post; &lt;a href="http://leecampbell.blogspot.com/2010/08/rx-part-7-hot-and-cold-observables.html"&gt;Part 7 - Hot and Cold observables&lt;/a&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:7197acfc-ec73-4312-9517-d913ba730b3e" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-966330026506466762?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/966330026506466762/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=966330026506466762' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/966330026506466762'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/966330026506466762'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/06/rx-part-6-scheduling-and-threading.html' title='Rx Part 6 – Scheduling and Threading'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-7207290344837671412</id><published>2010-06-19T17:04:00.001+01:00</published><updated>2011-03-14T07:58:12.079Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>RX Part 5 – Combining multiple IObservable&lt;T&gt; streams</title><content type='html'> In the last post we covered some of the flow control features of Rx and how to conceptualise them with Marble diagrams. This post will continue to build on those concepts by looking at different ways of working with multiple streams.    &lt;p&gt;The &lt;strong&gt;Concat&lt;/strong&gt; extension method is probably the most simple extension method. If you have covered the &lt;a title="Rx Part 4 - Flow control" href="http://leecampbell.blogspot.com/2010/05/rx-part-4-flow-control.html"&gt;previous flow control post&lt;/a&gt; then most of the error handling constructs are more complex than this method. The method will simple publish values from the second stream once the first stream completes.&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;//Generate values 0,1,2&lt;/span&gt;
var stream1 = Observable.Generate(0, i =&amp;gt; i &amp;lt; 3, i =&amp;gt; i, i =&amp;gt; i + 1);
&lt;span class="rem"&gt;//Generate values 100,101,102,103,104&lt;/span&gt;
var stream2 = Observable.Generate(100, i =&amp;gt; i &amp;lt; 105, i =&amp;gt; i, i =&amp;gt; i + 1);

stream1
    .Concat(stream2)
    .Subscribe(Console.WriteLine);
Console.ReadLine();
&lt;span class="rem"&gt;/* Returns:&lt;/span&gt;
&lt;span class="rem"&gt; * &lt;/span&gt;
&lt;span class="rem"&gt; * stream1 --0--0--0--|&lt;/span&gt;
&lt;span class="rem"&gt; * stream2 -----------0--0--0--0--|&lt;/span&gt;
&lt;span class="rem"&gt; * &lt;/span&gt;
&lt;span class="rem"&gt; * result  --0--0--0--0--0--0--0--|&lt;/span&gt;
&lt;span class="rem"&gt; */&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;If either stream was to OnError then the result stream would OnError too. This means that if &lt;em&gt;stream1&lt;/em&gt; produced an OnError then &lt;em&gt;stream2&lt;/em&gt; would never be used. If you wanted &lt;em&gt;stream2&lt;/em&gt; to be used regardless of if &lt;em&gt;stream1&lt;/em&gt; produced an OnError or not then the extension method &lt;em&gt;OnErrorResumeNext&lt;/em&gt; would be your best option.&lt;/p&gt;

&lt;p&gt;Quick Video on &lt;a title="Concat Catch and OnErrorResumeNext on channel9.msdn.com" href="http://channel9.msdn.com/posts/J.Van.Gogh/Rx-API-in-depth-Concat-Catch-and-OnErrorResumeNext/" target="_blank"&gt;Concat, Catch and OnErrorResume next on Channel9&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;strong&gt;Amb&lt;/strong&gt; method was a new concept to me. I believe this comes from functional programming and is an abbreviation of Ambiguous. Effectively this extension method will produce values from the stream that first produces values and will completely ignore the other stream. In the examples below I have 2 streams that both produce values. In the first example &lt;em&gt;stream1&lt;/em&gt; will win the race and the result stream will be &lt;em&gt;stream1&lt;/em&gt;’s values. In the second example, I delay the &lt;em&gt;stream1&lt;/em&gt; from producing values so &lt;em&gt;stream2&lt;/em&gt; will win the race and the result stream will be the values from &lt;em&gt;stream2&lt;/em&gt;.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;//Generate values 0,1,2&lt;/span&gt;
var stream1 = Observable.Range(0,3);
&lt;span class="rem"&gt;//Generate values 100,101,102,103,104&lt;/span&gt;
var stream2 = Observable.Range(100,5);

stream1
    .Amb(stream2)
    .Subscribe(Console.WriteLine);
Console.ReadLine();
&lt;span class="rem"&gt;/* Returns:&lt;/span&gt;
&lt;span class="rem"&gt; *  if stream 1 produces a value first...&lt;/span&gt;
&lt;span class="rem"&gt; * stream1 --0--0--0--|&lt;/span&gt;
&lt;span class="rem"&gt; * stream2 ---0--0--0--0--0--|&lt;/span&gt;
&lt;span class="rem"&gt; * &lt;/span&gt;
&lt;span class="rem"&gt; * result  --0--0--0--|     //All from stream1&lt;/span&gt;
&lt;span class="rem"&gt; */&lt;/span&gt;

stream1.Delay(TimeSpan.FromMilliseconds(100))
    .Amb(stream2)
    .Subscribe(Console.WriteLine);
Console.ReadLine();
&lt;span class="rem"&gt;/* Returns:&lt;/span&gt;
&lt;span class="rem"&gt; * stream1 ---0--0--0--|&lt;/span&gt;
&lt;span class="rem"&gt; * stream2 --0--0--0--0--0--|&lt;/span&gt;
&lt;span class="rem"&gt; * &lt;/span&gt;
&lt;span class="rem"&gt; * result  --0--0--0--0--0--|     //All from stream2&lt;/span&gt;
&lt;span class="rem"&gt; */&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;strong&gt;Merge&lt;/strong&gt; extension method does a primitive combination of multiple streams where they implement the same type of T. The result will also be an IObservable&amp;lt;T&amp;gt; but will have the values produced to the result stream as the occur in the source streams. The stream will complete when all of the source streams complete or when an OnError is published by any stream.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;//Generate values 0,1,2&lt;/span&gt;
var stream1 = Observable.Interval(TimeSpan.FromMilliseconds(250)).Take(3);
&lt;span class="rem"&gt;//Generate values 100,101,102,103,104&lt;/span&gt;
var stream2 = Observable.Interval(TimeSpan.FromMilliseconds(150)).Take(5).Select(i =&amp;gt; i + 100);
stream1
    .Merge(stream2)
    .Subscribe(Console.WriteLine);
Console.ReadLine();
&lt;span class="rem"&gt;/*&lt;/span&gt;
&lt;span class="rem"&gt; * Returns:&lt;/span&gt;
&lt;span class="rem"&gt; * stream1 ----0----0----0|&lt;/span&gt;
&lt;span class="rem"&gt; * stream2 --0--0--0--0--0|&lt;/span&gt;
&lt;span class="rem"&gt; * &lt;/span&gt;
&lt;span class="rem"&gt; * result  --0-00--00-0--00-|  &lt;/span&gt;
&lt;span class="rem"&gt; * Output:&lt;/span&gt;
&lt;span class="rem"&gt; * 100&lt;/span&gt;
&lt;span class="rem"&gt; * 0&lt;/span&gt;
&lt;span class="rem"&gt; * 101&lt;/span&gt;
&lt;span class="rem"&gt; * 102&lt;/span&gt;
&lt;span class="rem"&gt; * 1&lt;/span&gt;
&lt;span class="rem"&gt; * 103&lt;/span&gt;
&lt;span class="rem"&gt; * 104      //Note this is a race condition. 2 could be&lt;/span&gt;
&lt;span class="rem"&gt; * 2        //  published before 104.&lt;/span&gt;
&lt;span class="rem"&gt; */&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Merge&lt;/strong&gt; also provides other overloads that allow you to pass more than 2 source observables via an IEnumerable or params arrays. The Overload that take a params array it great for when we know how many streams we want to merge at compile time, and the IEnumerable overload is better for when we dont know at compile time how many streams we need to merge.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;//Create a third stream&lt;/span&gt;
var stream3 = Observable.Interval(TimeSpan.FromMilliseconds(100)).Take(10).Select(i =&amp;gt; i + 200);

&lt;span class="rem"&gt;//Number of streams known at compile time.&lt;/span&gt;
Observable.Merge(stream1, stream2, stream3)
    .Subscribe(Console.WriteLine);
Console.ReadLine();

&lt;span class="rem"&gt;//We can dynamically create a list at run time with this overload.&lt;/span&gt;
var streams = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;IObservable&amp;lt;&lt;span class="kwrd"&gt;long&lt;/span&gt;&amp;gt;&amp;gt;();
streams.Add(stream1);
streams.Add(stream2);
streams.Add(stream3);
Observable.Merge(streams).Subscribe(Console.WriteLine);
Console.ReadLine();&lt;/pre&gt;

&lt;p&gt;A quick video on &lt;a title="Merge on Channel9.msdn.com" href="http://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-Merge/" target="_blank"&gt;Merge on Channe9&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;SelectMany&lt;/strong&gt;, like it’s counter part in IEnumerable&amp;lt;T&amp;gt; extension method will create the &lt;a href="http://en.wikipedia.org/wiki/Cartesian_product"&gt;Caretisan product&lt;/a&gt; of the two streams. So for every item in one stream, it will give you every item in the other stream. A primitive way to think of it is a nexted for loop that creates a 2D array. If you want more info on &lt;strong&gt;SelectMany&lt;/strong&gt; I will leave it to you to do a google search as this fairly well documented in the IEnumerable world. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;//Generate values 0,1,2&lt;/span&gt;
var stream1 = Enumerable.Range(0, 3).ToObservable();
&lt;span class="rem"&gt;//Generate values 100,101,102,103,104&lt;/span&gt;
var stream2 = Enumerable.Range(100, 5).ToObservable();
stream1
    .SelectMany(i =&amp;gt; stream2, (lhs, rhs) =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; { Left = lhs, Right = rhs })
    .Subscribe(Console.WriteLine);
Console.ReadLine();
&lt;span class="rem"&gt;/*&lt;/span&gt;
&lt;span class="rem"&gt; * Output.&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 0, Right = 100 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 0, Right = 101 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 1, Right = 100 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 0, Right = 102 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 1, Right = 101 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 2, Right = 100 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 0, Right = 103 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 1, Right = 102 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 2, Right = 101 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 0, Right = 104 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 1, Right = 103 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 2, Right = 102 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 1, Right = 104 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 2, Right = 103 }&lt;/span&gt;
&lt;span class="rem"&gt; * { Left = 2, Right = 104 }&lt;/span&gt;
&lt;span class="rem"&gt; */&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;A quick Video on &lt;a title="SelectMany on Channel9.msdn.com" href="http://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-SelectMany/" target="_blank"&gt;SelectMany on channel9&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Zip&lt;/strong&gt; is another interesting merge feature. Just like a Zipper on clothing or a bag, the &lt;strong&gt;Zip&lt;/strong&gt; method will bring together two sets of values as pairs; two-by-two. Things to note about the &lt;strong&gt;Zip&lt;/strong&gt; function is that the result stream will complete when the first of the streams complete, it will error if either of the streams error and it will only publish once it was a pair. So if one of the source streams publish values faster than the other stream, the rate of publishing will be dictated by the slower of the two streams.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;//Generate values 0,1,2&lt;/span&gt;
var stream1 = Observable.Interval(TimeSpan.FromMilliseconds(250)).Take(3);
&lt;span class="rem"&gt;//Generate values a,b,c,d,e,f&lt;/span&gt;
var stream2 = Observable.Interval(TimeSpan.FromMilliseconds(150)).Take(6).Select(i =&amp;gt; Char.ConvertFromUtf32((&lt;span class="kwrd"&gt;int&lt;/span&gt;)i + 97));
stream1
    .Zip(stream2, (lhs, rhs) =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; { Left = lhs, Right = rhs })
    .Subscribe(Console.WriteLine);
Console.ReadLine();
&lt;span class="rem"&gt;/* Returns:&lt;/span&gt;
&lt;span class="rem"&gt; * stream1 ----0----1----2|        stream 1 values represented as ints&lt;/span&gt;
&lt;span class="rem"&gt; * stream2 --a--b--c--d--e--f|   s2 values represented as chars&lt;/span&gt;
&lt;span class="rem"&gt; * &lt;/span&gt;
&lt;span class="rem"&gt; * result  ----0----1----2|&lt;/span&gt;
&lt;span class="rem"&gt; *             a    b    c&lt;/span&gt;
&lt;span class="rem"&gt; */&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Here are two short videos on Zip (&lt;a title="Zip on Channel9.msdn.com" href="http://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-Zip/" target="_blank"&gt;first&lt;/a&gt;, &lt;a title="Second (and incorrect) Zip video on Channel9.msdn.com" href="http://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-even-more-Zip/" target="_blank"&gt;second&lt;/a&gt;)on Channel9. Note the second video is actually incorrect, can you spot why?&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CombineLatest&lt;/strong&gt; is worth comparing to the zip method. Both methods will use a function that takes a value from each stream to produce the result value. The difference is that &lt;strong&gt;CombineLatest&lt;/strong&gt; will cache the last value of each stream, and when either stream produces a new value then that new value and that last value from the other stream will be sent to the r&lt;em&gt;esult&lt;/em&gt; function. This example uses the same inputs as the previous &lt;strong&gt;Zip&lt;/strong&gt; example but note that many more values are produced. The leaves &lt;strong&gt;CombineLatest&lt;/strong&gt; somewhere between &lt;strong&gt;Zip&lt;/strong&gt; and &lt;strong&gt;SelectMany&lt;/strong&gt; :-)&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;//Generate values 0,1,2&lt;/span&gt;
var stream1 = Observable.Interval(TimeSpan.FromMilliseconds(250)).Take(3);
&lt;span class="rem"&gt;//Generate values a,b,c,d,e,f&lt;/span&gt;
var stream2 = Observable.Interval(TimeSpan.FromMilliseconds(150)).Take(6).Select(i =&amp;gt; Char.ConvertFromUtf32((&lt;span class="kwrd"&gt;int&lt;/span&gt;)i + 97));
stream1
    .CombineLatest(stream2, (s1, s2) =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; { Left = s1, Right = s2 })
    .Subscribe(Console.WriteLine, () =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Complete&amp;quot;&lt;/span&gt;));
Console.ReadLine();
&lt;span class="rem"&gt;/*&lt;/span&gt;
&lt;span class="rem"&gt; * Returns:&lt;/span&gt;
&lt;span class="rem"&gt; * stream1 ----0----1----2|        stream 1 values represented as ints&lt;/span&gt;
&lt;span class="rem"&gt; * stream2 --a--b--c--d--e--f|     stream 2 values represented as chars&lt;/span&gt;
&lt;span class="rem"&gt; * &lt;/span&gt;
&lt;span class="rem"&gt; * result  ----00--01-1--22-2|     the result as pairs.&lt;/span&gt;
&lt;span class="rem"&gt; *             ab  cc d  de f    &lt;/span&gt;
&lt;span class="rem"&gt; */&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Quick video on &lt;a title="CombineLatest on Channel9.msdn.com" href="http://channel9.msdn.com/posts/J.Van.Gogh/Reactive-Extensions-API-in-depth-CombineLatest/" target="_blank"&gt;CombineLatest on Channel9&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ForkJoin&lt;/strong&gt; like the last few extension methods also requires a function to produce the result but this will only return the last values from each stream. Things to note with &lt;strong&gt;ForkJoin&lt;/strong&gt; is that like the previous methods, if either stream error so will the result stream, but if either stream is empty (ie completes with no values) then the result stream will also be empty. This example uses the same values as the previous samples and will only produce a pair from the last values from each stream once they both complete. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="rem"&gt;//Generate values 0,1,2&lt;/span&gt;
var stream1 = Observable.Interval(TimeSpan.FromMilliseconds(250)).Take(3);
&lt;span class="rem"&gt;//Generate values a,b,c,d,e&lt;/span&gt;
var stream2 = Observable.Interval(TimeSpan.FromMilliseconds(150)).Take(5).Select(i =&amp;gt; Char.ConvertFromUtf32((&lt;span class="kwrd"&gt;int&lt;/span&gt;)i + 97));
stream1
    .ForkJoin(stream2, (s1, s2) =&amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; { Left = s1, Right = s2 })
    .Subscribe(Console.WriteLine);
Console.ReadLine();
&lt;span class="rem"&gt;/*&lt;/span&gt;
&lt;span class="rem"&gt; * Returns:&lt;/span&gt;
&lt;span class="rem"&gt; * stream1 ----0----1----2|        stream 1 values represented as ints&lt;/span&gt;
&lt;span class="rem"&gt; * stream2 --a--b--c--d--e|   s2 values represented as chars&lt;/span&gt;
&lt;span class="rem"&gt; * &lt;/span&gt;
&lt;span class="rem"&gt; * result  --------------2|   the result as pairs. &lt;/span&gt;
&lt;span class="rem"&gt; *                       e     &lt;/span&gt;
&lt;span class="rem"&gt; */&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;One thing to note with most of the extension methods discussed is that they generally have a matching static method that takes a params array or IEnumerable as discussed in the Merge chapter. &lt;/p&gt;

&lt;p&gt;So having looked at these ways to bring multiple observables together we have implicitly brought some concurrency and threading to our code. This allows us to nicely lead into the next post in the series which will be on Scheduling and Threading with Rx.&lt;/p&gt;

&lt;p&gt;The full source code is now available either via svn at &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or as a &lt;a href="http://rx-samples.googlecode.com/files/rx-samples_v008.zip"&gt;zip file&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Back to the &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;contents&lt;/a&gt; page for &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions for .NET Introduction&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Back to the previous post; &lt;a href="http://leecampbell.blogspot.com/2010/05/rx-part-4-flow-control.html"&gt;Part 4 - Flow control&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Forward to next post; &lt;a href="http://leecampbell.blogspot.com/2010/06/rx-part-6-scheduling-and-threading.html"&gt;Part 6 - Scheduling and threading&lt;/a&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:06263300-e1a3-40d1-b2e2-4a442319c595" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-7207290344837671412?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/7207290344837671412/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=7207290344837671412' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7207290344837671412'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7207290344837671412'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/06/rx-part-5-combining-multiple.html' title='RX Part 5 – Combining multiple IObservable&amp;lt;T&amp;gt; streams'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-8973791481799552589</id><published>2010-05-29T11:37:00.001+01:00</published><updated>2011-03-14T07:57:48.920Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>RX part 4 – Flow control</title><content type='html'> In the previous post we looked at the lifecycle of a subscription to a stream. A subscription can be terminated by unsubscribing/disposing and the stream (IObservable&amp;lt;T&amp;gt;) can terminate due to it completing naturally via an OnCompleted or erroneously with an OnError. OnError creates an interesting problem; it publishes the Exception, it does not throw it. This means that you can not use the standard Structured Exception Handling process of try/catch with Observables. Well that is not entirely true. In this example the stream raises an OnError that we can catch with a try/catch block thanks to the extension method overload of subscribe I use. It will take an OnError and then throw the Exception.    &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;try&lt;/span&gt;
{
    var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();
    subject.Subscribe(Console.WriteLine);
    &lt;span class="rem"&gt;//Or explicitly rethrow as per this line.&lt;/span&gt;
    &lt;span class="rem"&gt;//subject.Subscribe(Console.WriteLine, ex =&amp;gt; { throw ex.PrepareForRethrow(); });&lt;/span&gt;
    subject.OnNext(1);
    subject.OnError(&lt;span class="kwrd"&gt;new&lt;/span&gt; IOException(&lt;span class="str"&gt;&amp;quot;test exception&amp;quot;&lt;/span&gt;));
}
&lt;span class="kwrd"&gt;catch&lt;/span&gt; (IOException ioEx)
{
    Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Caught IO exception: {0}&amp;quot;&lt;/span&gt;, ioEx.Message);
}&lt;/pre&gt;

&lt;p&gt;Throwing published OnError exceptions does not allow for a very composable style of coding. It may be useful in cases like the example above, but the power of Rx as you will see in future posts is the ability to create compositions of streams together. Once we are running compositions of streams then SEH is not very helpful or useful. Rx provides several methods to provide a composition friendly way to handle errors and exceptions.&lt;/p&gt;

&lt;h4&gt;Visualising streams&lt;/h4&gt;

&lt;p&gt;Before I cover the flow control methods that Rx offers I want to divert quickly and talk about a visual tool we will use to help communicate the concepts relating to streams. Marble diagrams are great for communicating Rx streams and you may find them useful for describing any stream, except for the completely basic. When using marble diagrams to communicate Rx streams there are only a few things you need to know&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;a stream is represented by a horizontal line &lt;/li&gt;

  &lt;li&gt;time moves to the right (ie things on the left happened before things on the right) &lt;/li&gt;

  &lt;li&gt;we only need 3 symbols to represent an Event 
    &lt;ol&gt;
      &lt;li&gt;“0” for OnNext &lt;/li&gt;

      &lt;li&gt;“X” for an OnError &lt;/li&gt;

      &lt;li&gt;“|” for OnCompleted &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This is a sample of a stream that publishes 3 values and then completes&lt;/p&gt;

&lt;pre class="csharpcode"&gt;--0--0--0—|&lt;/pre&gt;

&lt;p&gt;This is a sample of a stream that publishes 4 values then errors.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;--0--0--0--0--X&lt;/pre&gt;

&lt;p&gt;While these examples may seem too simple to warrant a visual representation, the simplicity of marble diagrams are great once we using multiple streams.&lt;/p&gt;

&lt;h4&gt;Flow control constructs&lt;/h4&gt;

&lt;p&gt;Sometimes when dealing with an observable, it is conceivable that errors may occur that are acceptable and we should try again. Imagine that we want this effect where the error in stream 1 (S1) is acceptable, we try again on stream 2 (S2). The last line is composition of the two streams that is the result we want to expose (R)&lt;/p&gt;

&lt;pre class="csharpcode"&gt;S1--0--0--X
S2-----------0--0--0--0
R --0--0-----0--0--0--0&lt;/pre&gt;

&lt;p&gt;In the example above we could recreate this with several methods.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Retry&lt;/strong&gt; is the most simple method available to us. Retry will try to re-subscribe to the IObservable&amp;lt;T&amp;gt; on any failure. In this example we just use the simple overload that will always retry on any exception.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; RetrySample&amp;lt;T&amp;gt;(IObservable&amp;lt;T&amp;gt; stream)
{
    stream.Retry().Subscribe(t=&amp;gt;Console.WriteLine(t)); &lt;span class="rem"&gt;//Will always retry the stream&lt;/span&gt;
    Console.ReadKey();
}
&lt;span class="rem"&gt;/*&lt;/span&gt;
&lt;span class="rem"&gt;Given stream that will produce 0,1,2 then error; the output would be&lt;/span&gt;
&lt;span class="rem"&gt;0&lt;/span&gt;
&lt;span class="rem"&gt;1&lt;/span&gt;
&lt;span class="rem"&gt;2&lt;/span&gt;
&lt;span class="rem"&gt;0&lt;/span&gt;
&lt;span class="rem"&gt;1&lt;/span&gt;
&lt;span class="rem"&gt;2&lt;/span&gt;
&lt;span class="rem"&gt;0&lt;/span&gt;
&lt;span class="rem"&gt;1&lt;/span&gt;
&lt;span class="rem"&gt;2&lt;/span&gt;
&lt;span class="rem"&gt;.....&lt;/span&gt;
&lt;span class="rem"&gt;*/&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;which would look like this as a marble diagram&lt;/p&gt;

&lt;pre class="csharpcode"&gt;S--0--0--0--x--0--0--0--x--0--0--0--
R--0--0--0-----0--0--0-----0--0--0--&lt;/pre&gt;

&lt;p&gt;Alternatively we can specify the max number of times to retry. In this example we only retry once, therefore the error that gets published on the second subscription will be passed up to the final subscription. Note that to retry once you pass a value of 2. Maybe the method should be called &lt;em&gt;Try&lt;/em&gt;?&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; RetryOnceSample&amp;lt;T&amp;gt;(IObservable&amp;lt;T&amp;gt; stream)
{
    stream.Retry(2)
        .Subscribe(t=&amp;gt;Console.WriteLine(t), 
		 ex=&amp;gt;Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Gave up on 2nd Error&amp;quot;&lt;/span&gt;)); 
    Console.ReadKey();
}
&lt;span class="rem"&gt;/*Ouput:&lt;/span&gt;
&lt;span class="rem"&gt;0&lt;/span&gt;
&lt;span class="rem"&gt;1&lt;/span&gt;
&lt;span class="rem"&gt;2&lt;/span&gt;
&lt;span class="rem"&gt;0&lt;/span&gt;
&lt;span class="rem"&gt;1&lt;/span&gt;
&lt;span class="rem"&gt;2&lt;/span&gt;
&lt;span class="rem"&gt;Gave up on 2nd Error&lt;/span&gt;
&lt;span class="rem"&gt;*/&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;As a marble diagram this would look like&lt;/p&gt;

&lt;pre class="csharpcode"&gt;S--0--0--0--x--0--0--0--x
R--0--0--0-----0--0--0--x&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;OnErrorResumeNext&lt;/strong&gt; may cause some old VB developers to shudder but it offers a different route to use than Retry. While retry will always try to re-subscribe to the same stream; OnErrorResumeNext takes another IObservable&amp;lt;T&amp;gt; as a parameter to use when the original stream publishes and error. In this example when the stream1 publishes and error we re-subscribe to stream2.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; FailoverSample&amp;lt;T&amp;gt;(IObservable&amp;lt;T&amp;gt; stream, IObservable&amp;lt;T&amp;gt; failover)
{
    stream
        .OnErrorResumeNext(failover)
        .Subscribe(t=&amp;gt;Console.WriteLine(t), ex =&amp;gt; Console.WriteLine(ex));
}
&lt;span class="rem"&gt;/*&lt;/span&gt;
&lt;span class="rem"&gt;stream  --&amp;quot;1&amp;quot;--&amp;quot;2&amp;quot;--&amp;quot;3&amp;quot;--X&lt;/span&gt;
&lt;span class="rem"&gt;failover--------------------&amp;quot;a&amp;quot;--&amp;quot;b&amp;quot;--&amp;quot;c&amp;quot;--X&lt;/span&gt;
&lt;span class="rem"&gt;result  --&amp;quot;1&amp;quot;--&amp;quot;2&amp;quot;--&amp;quot;3&amp;quot;-----&amp;quot;a&amp;quot;--&amp;quot;b&amp;quot;--&amp;quot;c&amp;quot;--|&lt;/span&gt;
&lt;span class="rem"&gt;*/&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;An important thing to note here is that when the second stream publishes an error the result stream just completes and ignores the error.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Catch&lt;/strong&gt; is probably the most useful method to use as the previous 2 methods will react the same regardless of the type of exception published. Catch however allows you to specify which exceptions it can catch just like a normal catch block. This example is similar to the last example, but we will explicitly state the exception we should catch that would allow us to failover to the next stream.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; CatchSample&amp;lt;T&amp;gt;(IObservable&amp;lt;T&amp;gt; stream, IObservable&amp;lt;T&amp;gt; failover)
{
    stream
        .Catch((InvalidOperationException ex) =&amp;gt; failover)
        .Subscribe(t =&amp;gt; Console.WriteLine(t), 
                   ex =&amp;gt; Console.WriteLine(ex), 
                   () =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Completed&amp;quot;&lt;/span&gt;));
}&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Catch&lt;/em&gt; has other overloads that allow you to pass a params array of Observable&amp;lt;T&amp;gt; or an Enumerable&amp;lt;Observable&amp;lt;T&amp;gt;&amp;gt; instead of just specifying an intial and a failover stream. This means you can effectively have a large list of streams to try when a previous one fails. Of course if any of them actually complete then the next one will not be used. If the last one publishes an OnError then that error will then be published to the IObservalbe that the Catch method returned.&lt;/p&gt;

&lt;p&gt;Another pair of interesting methods is the &lt;strong&gt;Materialize&lt;/strong&gt; and &lt;strong&gt;Dematerialize&lt;/strong&gt; methods. Materialize will flatten an observable’s three different publication types (OnNext, OnError &amp;amp; OnCompleted) into wrapped publications of a Notifcation&amp;lt;T&amp;gt; type. Notification&amp;lt;T&amp;gt; is an abstract class that exposes 4 properties and an Overloaded Accept method&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Notification&amp;lt;T&amp;gt; : IEquatable&amp;lt;Notification&amp;lt;T&amp;gt;&amp;gt;
{
    &lt;span class="rem"&gt;// Properties&lt;/span&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; Exception Exception { get; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; HasValue { get; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; NotificationKind Kind { get; }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; T Value { get; }

    &lt;span class="rem"&gt;// Methods&lt;/span&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; TResult Accept&amp;lt;TResult&amp;gt;(IObserver&amp;lt;T, TResult&amp;gt; observer);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Accept(IObserver&amp;lt;T&amp;gt; observer);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Accept(Action&amp;lt;T&amp;gt; onNext, Action&amp;lt;Exception&amp;gt; onError, Action onCompleted);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; TResult Accept&amp;lt;TResult&amp;gt;(Func&amp;lt;T, TResult&amp;gt; onNext, Func&amp;lt;Exception, TResult&amp;gt; onError, Func&amp;lt;TResult&amp;gt; onCompleted);

    &lt;span class="rem"&gt;// ...&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;By inspecting the &lt;em&gt;Kind&lt;/em&gt; property you can identify which type of publication you have received. If the Kind is OnError you can access its published Exception via the Exception property. Accessing the Value property will get you either &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;the OnNext value, &lt;/li&gt;

  &lt;li&gt;throw the OnError exception &lt;/li&gt;

  &lt;li&gt;or throw an InvalidOperationException if the Kind is OnCompleted &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The HasValue property just provides the convenience to check if the Kind is OnNext so you can safely get the value without having an exception thrown.&lt;/p&gt;

&lt;p&gt;As you can imagine the Materialise method can be useful for Logging the content of a stream. In this example we create an extension method that logs all events to the Console.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ExampleExtensions
{
    &lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
    &lt;span class="rem"&gt;/// Logs implicit notifications to console.&lt;/span&gt;
    &lt;span class="rem"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
    &lt;span class="rem"&gt;/// &amp;lt;example&amp;gt;&lt;/span&gt;
    &lt;span class="rem"&gt;/// &amp;lt;code&amp;gt;myStream.Log().Subscribe(....);&amp;lt;/code&amp;gt;&lt;/span&gt;
    &lt;span class="rem"&gt;/// &amp;lt;/example&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IObservable&amp;lt;T&amp;gt; Log&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IObservable&amp;lt;T&amp;gt; stream)
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; stream.Materialize()
        .Do(n =&amp;gt; Console.WriteLine(n))
        .Dematerialize();
    }
}&lt;/pre&gt;

&lt;p&gt;Note that here we use Dematerialize to take our stream of Notification&amp;lt;T&amp;gt; and transform it back to our original stream. You could also use Materialize to create your own more powerful Catch methods, but we will look at applications of Rx later.&lt;/p&gt;

&lt;h4&gt;Wire tapping a stream&lt;/h4&gt;

&lt;p&gt;The &lt;strong&gt;Do&lt;/strong&gt; extension method was used in the last example and it would not be fair to continue with out explaining what it does. &lt;em&gt;Do&lt;/em&gt; method is used to provide side effects upon a stream. In the example above the side-effect is that we wrote to the console. This is different to a &lt;em&gt;Subscribe&lt;/em&gt; because the &lt;em&gt;Do&lt;/em&gt; method returns you an IObservable&amp;lt;T&amp;gt; which can be thought of as the same IObservable&amp;lt;T&amp;gt; that was passed to it, however the Subscribe method returns you an IDisposable. I like to think of the &lt;em&gt;Do&lt;/em&gt; method as a &lt;a href="http://en.wikipedia.org/wiki/Telephone_tapping"&gt;wire tap&lt;/a&gt; to a stream. ;-)&lt;/p&gt;

&lt;p&gt;It would be unfair to mention &lt;em&gt;Do&lt;/em&gt; and leave out &lt;strong&gt;Run&lt;/strong&gt;. The &lt;em&gt;Run&lt;/em&gt; method is very similar to the &lt;em&gt;Do&lt;/em&gt; method except for two things:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;em&gt;Run&lt;/em&gt; returns void &lt;/li&gt;

  &lt;li&gt;&lt;em&gt;Run&lt;/em&gt; is a blocking call &lt;/li&gt;

  &lt;li&gt;&lt;em&gt;Run&lt;/em&gt; can be called without any parameters. This effectively is a call to block until OnCompleted or OnError is published. &lt;/li&gt;

  &lt;li&gt;&lt;em&gt;Run&lt;/em&gt; has no overload that takes an Action for the OnCompleted publication. It doesn't make sense to do so as the method will just stop blocking when OnCompleted is published so you can just invoke the action you would other wise pass to OnCompleted immediately after the &lt;em&gt;Run&lt;/em&gt; method returns. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The things in common with the Run and Do method overloads is they both provide an Overload that:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;takes an Action&amp;lt;T&amp;gt; to be performed on each OnNext publication. &lt;/li&gt;

  &lt;li&gt;takes an Action&amp;lt;T&amp;gt; for OnNext and an Action&amp;lt;Exception&amp;gt; for OnError publications &lt;/li&gt;

  &lt;li&gt;takes an IObserver&amp;lt;T&amp;gt; that will be used to handle the publications explicitly &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now that we have had a brief look at Flow control and aggregating streams together, in the next post we will uncover the other aggregation and composition methods that Rx exposes.&lt;/p&gt;

&lt;p&gt;The full source code is now available either via svn at &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or as a &lt;a href="http://rx-samples.googlecode.com/files/rx-samples_v008.zip"&gt;zip file&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Back to the &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;contents&lt;/a&gt; page for &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions for .NET Introduction&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Back to the previous post; &lt;a href="http://leecampbell.blogspot.com/2010/05/rx-part-3-lifetime-management.html"&gt;Part 3 - Lifetime management – Completing and Unsubscribing&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Forward to next post; &lt;a href="http://leecampbell.blogspot.com/2010/06/rx-part-5-combining-multiple.html"&gt;Part 5 - Combining multiple IObservable streams&lt;/a&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:476ee1db-a393-4b3a-b48c-76fd2f14271f" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-8973791481799552589?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/8973791481799552589/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=8973791481799552589' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/8973791481799552589'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/8973791481799552589'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/05/rx-part-4-flow-control.html' title='RX part 4 – Flow control'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-8184042274919941742</id><published>2010-05-27T19:47:00.001+01:00</published><updated>2011-03-14T07:57:22.519Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Rx Part 3 – Lifetime management – Completing and Unsubscribing</title><content type='html'> So far we have discovered the basics of&amp;#160; the Reactive Framework which allows us to create, subscribe and perform some basic aggregations, buffering and time shifting over implementations of IObservable&amp;lt;T&amp;gt;. We have yet to look at how we could unsubscribe from a subscription. If you were to look for an Unsubscribe method in the Rx public API you would not find any. Instead of supplying an Unsubscribe method, Rx will return an IDisposable when ever a subscription is made. This disposable can be thought of as the subscription itself and therefore disposing it will dispose the subscription and effectively &lt;em&gt;unsubscribe&lt;/em&gt;. Note that calling Dispose on the result of a Subscribe call will not affect the underlying IObservable&amp;lt;T&amp;gt;, just the instance of the subscription to the IObservable&amp;lt;T&amp;gt;. This then allows us to call Subscribe many times on a single IObservable&amp;lt;T&amp;gt;, allowing subscriptions to come an go with out affecting each other. In this example we initially have two subscriptions, then we dispose of one subscription early which still allows the other to continue to receive publications from the underlying IObservable&amp;lt;T&amp;gt;.    &lt;pre class="csharpcode"&gt;var interval = Observable.Interval(TimeSpan.FromMilliseconds(100));
var firstSubscription =
    interval.Subscribe(&lt;span class="kwrd"&gt;value&lt;/span&gt; =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;1st subscription recieved {0}&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;value&lt;/span&gt;));
var secondSubscription =
    interval.Subscribe(&lt;span class="kwrd"&gt;value&lt;/span&gt; =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;2nd subscription recieved {0}&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;value&lt;/span&gt;));

Thread.Sleep(500);
firstSubscription.Dispose();
Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Disposed of 1st subscription&amp;quot;&lt;/span&gt;);

Console.ReadKey();
&lt;span class="rem"&gt;/*Outputs:&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 0&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 0&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 1&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 1&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 2&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 2&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 3&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 3&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 4&lt;/span&gt;
&lt;span class="rem"&gt;Disposed of 1st subscription&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 5&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 6&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 7&lt;/span&gt;
&lt;span class="rem"&gt;&lt;/span&gt;
&lt;span class="rem"&gt;etc....&lt;/span&gt;
&lt;span class="rem"&gt;*/&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;In the above example, it looks like the values are being produced by the interval Observable by a single OnNext call, however these are independent and work similarly to how a Observable.Create&amp;lt;T&amp;gt; method would work. In this sample we just pause a bit before making our second subscription. Note that the output is different to the above example.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;p&gt;var interval = Observable.Interval(TimeSpan.FromMilliseconds(100));

var firstSubscription =
    interval.Subscribe(&lt;span class="kwrd"&gt;value&lt;/span&gt; =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;1st subscription recieved {0}&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;value&lt;/span&gt;));
Thread.Sleep(500);
var secondSubscription =
    interval.Subscribe(&lt;span class="kwrd"&gt;value&lt;/span&gt; =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;2nd subscription recieved {0}&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;value&lt;/span&gt;));

Thread.Sleep(500);
firstSubscription.Dispose();
Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Disposed of 1st subscription&amp;quot;&lt;/span&gt;);
&lt;span class="rem"&gt;/*&lt;/span&gt;
&lt;span class="rem"&gt;Ouput:&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 0&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 1&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 2&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 3&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 4&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 0 &lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 5&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 1&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 6&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 7&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 2&lt;/span&gt;
&lt;span class="rem"&gt;1st subscription recieved 8&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 3&lt;/span&gt;
&lt;span class="rem"&gt;Disposed of 1st subscription&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 4&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 5&lt;/span&gt;
&lt;span class="rem"&gt;2nd subscription recieved 6&lt;/span&gt;
&lt;span class="rem"&gt;etc...&lt;/span&gt;
&lt;span class="rem"&gt;&lt;/span&gt;
&lt;span class="rem"&gt;*/&lt;/span&gt;&lt;/p&gt;&lt;/pre&gt;

&lt;p&gt;The benefits of using the IDisposable Type instead of creating a new ISubscription/IUnsubscription interface or amending the IObservable&amp;lt;T&amp;gt; interface to have an Unsubscribe method is that you get all of these things for free:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The type already exists &lt;/li&gt;

  &lt;li&gt;people understand the type &lt;/li&gt;

  &lt;li&gt;IDisposable has standard usages and patterns &lt;/li&gt;

  &lt;li&gt;Language support via the Using keyword &lt;/li&gt;

  &lt;li&gt;Static analysis tools like FxCop can help you with its usage. &lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;OnError and OnCompleted()&lt;/h4&gt;

&lt;p&gt;Both the OnError and OnCompleted signify the completion of a stream. If your stream publishes a OnError or OnCompleted it will be the last publication and no further calls to OnNext can be performed. In this example we try to publish an OnNext call after an OnCompleted and the OnNext is ignored.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;();
subject.Subscribe(Console.WriteLine, () =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Completed&amp;quot;&lt;/span&gt;));
subject.OnCompleted();
subject.OnNext(2);&lt;/pre&gt;
Of course you could implement your own IObservable&amp;lt;T&amp;gt; that did allow publishing after an OnComplete or an OnError, however it would not follow the precedence of the current Subject types and would be a non standard implementation. I think it would be safe to say that the inconsistent behaviour would cause unpredictable behaviour in the applications that consumed your code. 

&lt;p&gt;An interesting thing to consider is that when a stream completes or errors, you should still dispose of you subscription. This can make for messy code, but we will discuss best practices in a later post.&lt;/p&gt;

&lt;p&gt;The full source code is now available either via svn at &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or as a &lt;a href="http://rx-samples.googlecode.com/files/rx-samples_v008.zip"&gt;zip file&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Back to the &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;contents&lt;/a&gt; page for &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions for .NET Introduction&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Back to the previous post; &lt;a href="http://leecampbell.blogspot.com/2010/05/rx-part-2-static-and-extension-methods.html"&gt;Part 2 - Static and extension methods&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Forward to next post; &lt;a href="http://leecampbell.blogspot.com/2010/05/rx-part-4-flow-control.html"&gt;Part 4 - Flow control&lt;/a&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:01c17df2-f633-4fc4-b4f3-43ec73f3dbcd" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-8184042274919941742?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/8184042274919941742/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=8184042274919941742' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/8184042274919941742'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/8184042274919941742'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/05/rx-part-3-lifetime-management.html' title='Rx Part 3 – Lifetime management – Completing and Unsubscribing'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-1211368060841026290</id><published>2010-05-23T10:23:00.005+01:00</published><updated>2011-07-02T19:18:23.031+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Rx part 2 – Static and Extension methods</title><content type='html'>In the &lt;a title="Intro to Rx" href="http://leecampbell.blogspot.com/2010/05/intro-to-rx.html"&gt;previous post&lt;/a&gt; we looked at the &lt;a title="Exploring the Major Interfaces in Rx - MSDN" href="http://msdn.microsoft.com/en-us/library/hh242974(v=VS.103).aspx"&gt;core types to the Rx library&lt;/a&gt; and how we could get up and running with “Observables”. The key types we discussed were the &lt;a title="IObservable(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd990377.aspx"&gt;IObservable&amp;lt;T&amp;gt;&lt;/a&gt; interface, &lt;a title="IObserver(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd783449.aspx"&gt;IObserver&amp;lt;T&amp;gt;&lt;/a&gt;, &lt;a title="Subject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh229173(v=VS.103).aspx"&gt;Subject&amp;lt;T&amp;gt;&lt;/a&gt; and its siblings &lt;a title="ReplaySubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh211810(v=VS.103).aspx"&gt;ReplaySubject&amp;lt;T&amp;gt;&lt;/a&gt;, &lt;a title="BehaviorSubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh211949(v=VS.103).aspx"&gt;BehaviorSubject&amp;lt;T&amp;gt;&lt;/a&gt; and &lt;a title="AsyncSubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh229363(v=VS.103).aspx"&gt;AsyncSubject&amp;lt;T&amp;gt;&lt;/a&gt;. In this post we are going to explore some of the Static methods on the Observable type and some &lt;a title="ObservableExtensions class - MSDN" href="http://msdn.microsoft.com/en-us/library/system.observableextensions(v=VS.103).aspx"&gt;Extension methods to the IObservable&amp;lt;T&amp;gt; interface&lt;/a&gt;.   &lt;p&gt;We have already seen on extension method in the last post which was the &lt;a title="Subscribe Extension method overloads on MSDN" href="http://msdn.microsoft.com/en-us/library/ff626574(v=VS.92).aspx"&gt;Overload to Subscribe&lt;/a&gt; which allowed us to pass just an &lt;a title="Action(Of T) Delegate - MSDN" href="http://msdn.microsoft.com/en-us/library/018hxwa8.aspx"&gt;Action&amp;lt;T&amp;gt;&lt;/a&gt; to be performed when OnNext was invoked instead of passing an &lt;a title="IObserver(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd783449.aspx"&gt;IObserver&amp;lt;T&amp;gt;&lt;/a&gt;. The other overloads of Subscribe are also very useful&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ObservableExtensions
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IDisposable Subscribe&amp;lt;TSource&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IObservable&amp;lt;TSource&amp;gt; source);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IDisposable Subscribe&amp;lt;TSource&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IObservable&amp;lt;TSource&amp;gt; source, Action&amp;lt;TSource&amp;gt; onNext);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IDisposable Subscribe&amp;lt;TSource&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IObservable&amp;lt;TSource&amp;gt; source, Action&amp;lt;TSource&amp;gt; onNext, Action&amp;lt;Exception&amp;gt; onError);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IDisposable Subscribe&amp;lt;TSource&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IObservable&amp;lt;TSource&amp;gt; source, Action&amp;lt;TSource&amp;gt; onNext, Action onCompleted);
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IDisposable Subscribe&amp;lt;TSource&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IObservable&amp;lt;TSource&amp;gt; source, Action&amp;lt;TSource&amp;gt; onNext, Action&amp;lt;Exception&amp;gt; onError, Action onCompleted);
} &lt;/pre&gt;

&lt;p&gt;Each of these overloads allows you to pass various combinations of delegates that you want executed for each publication event an &lt;a title="IObservable(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd990377.aspx"&gt;IObservable&amp;lt;T&amp;gt;&lt;/a&gt; could raise. You will use these overloads a lot but there are plenty of other static methods that are very helpful on the static &lt;a title="Observable static class - MSDN" href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable(v=VS.103).aspx"&gt;Observable class&lt;/a&gt;.&lt;/p&gt;

&lt;h4&gt;Creation and Generation of Observables&lt;/h4&gt;

&lt;p&gt;The &lt;a title="Observable static class - MSDN" href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable(v=VS.103).aspx"&gt;Observable class&lt;/a&gt; has several methods for conveniently creating common types of Observables. The most simple are shown below with an example of how to use it and what you would have to write to emulate the method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Observable.Empty&amp;lt;T&amp;gt;() &lt;/strong&gt;This returns IObservable&amp;lt;T&amp;gt; that just publishes an OnCompleted. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; ReplaySubject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
subject.OnCompleted();
&lt;span class="rem"&gt;//Or&lt;/span&gt;
var empty = Observable.Empty&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Observable.Return&amp;lt;T&amp;gt;(T)&lt;/strong&gt;. This method will return an Observable that publishes the value of T supplied and then publish OnCompleted.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; ReplaySubject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
subject.OnNext(&lt;span class="str"&gt;&amp;quot;Value&amp;quot;&lt;/span&gt;);
subject.OnCompleted();
&lt;span class="rem"&gt;//Or&lt;/span&gt;
var obReturn = Observable.Return(&lt;span class="str"&gt;&amp;quot;Value&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Observable.Never&amp;lt;T&amp;gt;()&lt;/strong&gt;. This method will return an IObservable&amp;lt;T&amp;gt; but will not publish any events.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
&lt;span class="rem"&gt;//Or&lt;/span&gt;
var never = Observable.Never&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Observable.Throw&amp;lt;T&amp;gt;(Exception)&lt;/strong&gt;. This method just publishes the exception passed.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; ReplaySubject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
subject.OnError(&lt;span class="kwrd"&gt;new&lt;/span&gt; Exception());
&lt;span class="rem"&gt;//Or&lt;/span&gt;
var throws = Observable.Throw&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;(&lt;span class="kwrd"&gt;new&lt;/span&gt; Exception());&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Observable.Create&amp;lt;T&amp;gt;(Func&amp;lt;IObserver&amp;lt;T&amp;gt;,IDisposable&amp;gt;)&lt;/strong&gt; is a little different to the above creation methods. The method signature itself is a bit nasty but once you get to know him, he is not that bad. Essentially this method allows you to specify a delegate that will be executed anytime a subscription is made. The &lt;a title="IObserver(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd783449.aspx"&gt;IObserver&amp;lt;T&amp;gt;&lt;/a&gt; that made the subscription will be passed to your delegate so that you can call the OnNext/OnError/OnCompleted methods as you need. Your delegate is a Func that returns an IDisposable. This IDisposable will have it’s Dispose method called when the subscriber disposes from their subscription. We will cover unsubscribing/disposing in a future post.&lt;/p&gt;

&lt;p&gt;The big benefit of using the Create method is that your method will be a non blocking call which is the whole point of the Rx framework. In this example we show how we might first return an Observable via standard blocking call, and then we show the correct way to return an Observable without blocking&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; IObservable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; BlockingMethod()
{
  var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; ReplaySubject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
  subject.OnNext(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
  subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
  subject.OnCompleted();
  Thread.Sleep(1000);
  &lt;span class="kwrd"&gt;return&lt;/span&gt; subject;
}
&lt;span class="kwrd"&gt;private&lt;/span&gt; IObservable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; NonBlocking()
{
  &lt;span class="kwrd"&gt;return&lt;/span&gt; Observable.Create&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;(
      observable =&amp;gt;
      {
        observable.OnNext(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
        observable.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
        observable.OnCompleted();
        Thread.Sleep(1000);
        &lt;span class="kwrd"&gt;return&lt;/span&gt; Disposable.Create(() =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Observer has unsubscribed&amp;quot;&lt;/span&gt;));
        &lt;span class="rem"&gt;//or can return an Action like&lt;/span&gt;
        &lt;span class="rem"&gt;//return () =&amp;gt; Console.WriteLine(&amp;quot;Observer has unsubscribed&amp;quot;);&lt;/span&gt;
      });
}&lt;/pre&gt;

&lt;p&gt;I would imagine that you will use Observable.Create&amp;lt;T&amp;gt; method a lot once you start using Rx. An obvious application of this method is if you needed to perform a slow request to the network (web service or SQL call). There is also a &lt;strong&gt;Observable.Create&amp;lt;T&amp;gt;(Func&amp;lt;IObserver&amp;lt;T&amp;gt;,Action&amp;gt;)&lt;/strong&gt; method that instead of invoking the Dispose method it will just invoke the action when the subscriber disposes their subscription.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Observable.Range(int, int)&lt;/strong&gt; returns just a range of integers. The first integer is the initial value and the second is the number of values to yield. This example will write the values &amp;quot;10” through to “24” and then “Completed”.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var range = Observable.Range(10, 15);
range.Subscribe(Console.WriteLine, ()=&amp;gt;Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Completed&amp;quot;&lt;/span&gt;));&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Observable.Interval(TimeSpan)&lt;/strong&gt; will publish incremental values from 0 every period that you supply.&amp;#160; This examples publishes values every 250milliseconds&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var interval = Observable.Interval(TimeSpan.FromMilliseconds(250));
interval.Subscribe(Console.WriteLine);&lt;/pre&gt;

&lt;p&gt;In this example I use the Observable.Interval method to fake ticking prices&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var rnd = &lt;span class="kwrd"&gt;new&lt;/span&gt; Random();
var lastPrice = 100.0;
var interval = Observable.Interval(TimeSpan.FromMilliseconds(250))
    .Select(i =&amp;gt;
      {
          var variation =
              rnd.NextDouble() - 0.5;
          lastPrice += variation;
          &lt;span class="kwrd"&gt;return&lt;/span&gt; lastPrice;
      });

interval.Subscribe(Console.WriteLine);&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Observable.Start&lt;/strong&gt; method allows you to turn a long running Func&amp;lt;T&amp;gt; or Action into an Observable. If you use the overload that takes an Action then the returned Observable will be of type IObservable&amp;lt;Unit&amp;gt;. Unit is analogous to void and is a Functional Programming construct. In this case it is just used to publish an acknowledgement that the Action is complete, however this is rather inconsequential as OnCompleted will be published straight after Unit anyway. If the overload you use is a Func&amp;lt;T&amp;gt; then when the Func returns its value it will be published and then OnCompleted. Below is an example of using both overloads.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; StartAction()
{
    var start = Observable.Start(() =&amp;gt;
    {
        Console.Write(&lt;span class="str"&gt;&amp;quot;Working away&amp;quot;&lt;/span&gt;);
        &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; 10; i++)
        {
            Thread.Sleep(100);
            Console.Write(&lt;span class="str"&gt;&amp;quot;.&amp;quot;&lt;/span&gt;);
        }
    });
    start.Subscribe(unit =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Unit published&amp;quot;&lt;/span&gt;), () =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Action completed&amp;quot;&lt;/span&gt;));
}
&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; StartFunc()
{
    var start = Observable.Start(() =&amp;gt;
    {
        Console.Write(&lt;span class="str"&gt;&amp;quot;Working away&amp;quot;&lt;/span&gt;);
        &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; 10; i++)
        {
            Thread.Sleep(100);
            Console.Write(&lt;span class="str"&gt;&amp;quot;.&amp;quot;&lt;/span&gt;);
        }
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="str"&gt;&amp;quot;Published value&amp;quot;&lt;/span&gt;;
    });
    start.Subscribe(Console.WriteLine, () =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Action completed&amp;quot;&lt;/span&gt;));
}&lt;/pre&gt;
&lt;style type="text/css"&gt;





.csharpcode, .csharpcode pre
{
 font-size: small;
 color: black;
 font-family: consolas, "Courier New", courier, monospace;
 background-color: #ffffff;
 /*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
 background-color: #f4f4f4;
 width: 100%;
 margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;&lt;strong&gt;ToObservable&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt;)&lt;/strong&gt; is an extension method for IEnumerable&amp;lt;T&amp;gt; that will translate any IEnumerable&amp;lt;T&amp;gt; to an IObservable&amp;lt;T&amp;gt;. It is a simple an convenient method for switching from one paradigm to another.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var enumT =  &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
enumT.Add(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
enumT.Add(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
enumT.Add(&lt;span class="str"&gt;&amp;quot;c&amp;quot;&lt;/span&gt;);
var fromEnum = enumT.ToObservable();

fromEnum.Subscribe(Console.WriteLine);&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;ToEnumerable&amp;lt;T&amp;gt;(this IObservable&amp;lt;T&amp;gt;)&lt;/strong&gt; effectively is the opposite of the above method. It will take an IObservable&amp;lt;T&amp;gt; and yield its results as an IEnumerable. Again useful for switching paradigms.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Observable.Generate&lt;/strong&gt; provides a more elaborate way to construct Observables than Range. In this example I keep it simple and have the Generate method construct me a sequence starting from 5 and incrementing by 3 while the value is less than 15. I also have the values published as strings to show that the type of the State and Result can be different.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var generated = Observable.Generate(5, i =&amp;gt; i &amp;lt; 15, i =&amp;gt; i + 3, i =&amp;gt; i.ToString());
generated.Subscribe(Console.WriteLine, ()=&amp;gt;Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Completed&amp;quot;&lt;/span&gt;));&lt;/pre&gt;

&lt;h4&gt;Checking for existence&lt;/h4&gt;

&lt;p&gt;Theses method below all provide some sort of check to confirm the existence of a published value.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Any&amp;lt;T&amp;gt;(this IObservable&amp;lt;T&amp;gt;)&lt;/strong&gt; is an extension method that will either check that the IObservable will publish any value at all, or if you use the overload that take a Func&amp;lt;T,bool&amp;gt; then it will check if any values satisfy your predicate. The interesting thing about Any is that it is non-blocking and so returns an IObservable&amp;lt;bool&amp;gt;. This will only yield one value.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var range = Observable.Range(10, 15);
range.Any().Subscribe(Console.WriteLine);
range.Any(i =&amp;gt; i &amp;gt; 100).Subscribe(Console.WriteLine);
Observable.Empty&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;().Any().Subscribe(Console.WriteLine);&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Contains&amp;lt;T&amp;gt;(this IObservable&amp;lt;T&amp;gt;, T)&lt;/strong&gt; is an extension method like Any but will only accept a value of T not a predicate of T. Like Any the result is an IObservable&amp;lt;bool&amp;gt;.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var range = Observable.Range(10, 15);
range.Contains(15).Subscribe(Console.WriteLine);
Observable.Empty&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;().Contains(5).Subscribe(Console.WriteLine);&lt;/pre&gt;

&lt;h4&gt;Filtering and Aggregating&lt;/h4&gt;

&lt;p&gt;These next few extension methods provide some sort of filter to the underlying stream. These are very similar to the extension methods available to IEnumerable&amp;lt;T&amp;gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;First&amp;lt;T&amp;gt;(this IObservable&amp;lt;T&amp;gt;)&lt;/strong&gt; simply returns the first value of an Observable or throws InvalidOperationException if the stream completes without yielding a value. This is a blocking call that wont return until a value or OnCompleted is published.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var range = Observable.Range(10, 15);
Console.WriteLine(range.First());
&lt;span class="rem"&gt;//InvalidOperationException(&amp;quot;Sequence contains no elements.&amp;quot;)&lt;/span&gt;
Console.WriteLine(Observable.Empty&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;().First());&lt;/pre&gt;

&lt;p&gt;There are further extension methods that probably don't warrant further explanation if I assume you are familiar with the existing IEnumerable&amp;lt;T&amp;gt; extension methods. These include&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;FirstOrDefault &lt;/li&gt;

  &lt;li&gt;Last &lt;/li&gt;

  &lt;li&gt;LastOrDefault &lt;/li&gt;

  &lt;li&gt;Single &lt;/li&gt;

  &lt;li&gt;Count &lt;/li&gt;

  &lt;li&gt;Min &lt;/li&gt;

  &lt;li&gt;Max &lt;/li&gt;

  &lt;li&gt;Sum &lt;/li&gt;

  &lt;li&gt;Where &lt;/li&gt;

  &lt;li&gt;GroupBy &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;While I think that most of these are self explanatory, what maybe worth reinforcing is that some of the scalar methods (returns bool or T and not IObservable) are blocking calls. This can be very handy for transforming your non blocking Rx code into sequential blocking code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Aggregate &amp;amp; Scan&lt;/strong&gt; extension method overloads allow you to create your own aggregations. Both take similar arguments for their overloads. One of &lt;strong&gt;Scan&lt;/strong&gt;’s overload takes a Func&amp;lt;T,T,T&amp;gt; which is the more simple overload. Effectively given an accumulator and the current value you must return the next accumulator. The other overload can take another type for the accumulator and allows you to specify the seed value for accumulator. &lt;/p&gt;

&lt;p&gt;Aggregate has the same overloads. The difference is that Scan will OnNext the result of every Accumulation, Aggregate will only OnNext the last value. Therefore Aggregate is like an &lt;a title="AsyncSubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh229363(v=VS.103).aspx"&gt;AsyncSubject&amp;lt;T&amp;gt;&lt;/a&gt; version of Scan.&lt;/p&gt;

&lt;p&gt;In this example Scan will publish the running sum of the input sequence, and Aggregate will only publish the final total.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Aggregate_can_be_used_to_create_your_own_aggregates()
{
  var interval = Observable.Interval(TimeSpan.FromMilliseconds(150))
                          .Take(10);  &lt;span class="rem"&gt;//Must complete for Aggregate to publish a value.&lt;/span&gt;
  var aggregate = interval.Aggregate(0L, (acc, i) =&amp;gt; acc + i);
  WriteStreamToConsole(aggregate, &lt;span class="str"&gt;&amp;quot;aggregate&amp;quot;&lt;/span&gt;);
}

&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Scan_allows_custom_rolling_aggregation()
{
  var interval = Observable.Interval(TimeSpan.FromMilliseconds(150));
  var scan = interval.Scan(0L, (acc, i) =&amp;gt; acc + i);
  WriteStreamToConsole(scan, &lt;span class="str"&gt;&amp;quot;scan&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Take&amp;lt;T&amp;gt;(this IObservable&amp;lt;T&amp;gt;, int)&lt;/strong&gt; will return you the first number of publications specified by the integer value provided. Take(1) is like First() expect that is returns an IObservable so is not blocking. This example yields just the values 10 and 11.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var range = Observable.Range(10, 15);
range.Take(2).Subscribe(Console.WriteLine);&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Skip&amp;lt;T&amp;gt;(this IObservable&amp;lt;T&amp;gt;, int)&lt;/strong&gt; will ignore the first number of publications specified by the integer value provided. So while Take(2) above returned 10 and 11, Skip(2) will ignore 10 and 11 and return the rest of the stream.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var range = Observable.Range(10, 15);
range.Skip(2).Subscribe(Console.WriteLine);&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;DistinctUntilChanged&amp;lt;T&amp;gt;(this IObservable&amp;lt;T&amp;gt;)&lt;/strong&gt; &lt;em&gt;formerly HoldUntilChanged&lt;/em&gt;, will ignore any value that is the same as the previous value. In this example the values a, b and c are only written to the console once each.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
subject.DistinctUntilChanged().Subscribe(Console.WriteLine);
subject.OnNext(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
subject.OnNext(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
subject.OnNext(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
subject.OnNext(&lt;span class="str"&gt;&amp;quot;c&amp;quot;&lt;/span&gt;);
subject.OnNext(&lt;span class="str"&gt;&amp;quot;c&amp;quot;&lt;/span&gt;);
subject.OnNext(&lt;span class="str"&gt;&amp;quot;c&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

&lt;h4&gt;Buffering and time shifting&lt;/h4&gt;

&lt;p&gt;In some scenarios your application or user may not be able to keep up with the amount of data that a stream is providing. Alternatively, your user or application may just not need the amount of data that is being published. Rx offer some great extension methods for allowing you to control the rate at which values are published to your stream.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Buffer&lt;/strong&gt; allows you to buffer a range of values and then re-publish them as a list once the buffer is full. You can buffer a specified number of elements or buffer all the values per timespan&lt;strong&gt;. &lt;/strong&gt;Buffer also offer more advanced overloads.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
    var range = Observable.Range(10, 15);
    range.Buffer(4).Subscribe(
        enumerable =&amp;gt;
           {
               Console.WriteLine(&lt;span class="str"&gt;&amp;quot;--Buffered values&amp;quot;&lt;/span&gt;);
               enumerable.ToList().ForEach(Console.WriteLine);
           }, () =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Completed&amp;quot;&lt;/span&gt;));

    var interval = Observable.Interval(TimeSpan.FromMilliseconds(150));
    interval.Buffer(TimeSpan.FromSeconds(1)).Subscribe(
        enumerable =&amp;gt;
        {
            Console.WriteLine(&lt;span class="str"&gt;&amp;quot;--Buffered values&amp;quot;&lt;/span&gt;);
            enumerable.ToList().ForEach(Console.WriteLine);
        }, () =&amp;gt; Console.WriteLine(&lt;span class="str"&gt;&amp;quot;Completed&amp;quot;&lt;/span&gt;));

    Console.ReadKey();
}&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Delay&lt;/strong&gt; is an extension method overload that will time-shift the entire Observable by the TimeSpan specified, or until the DateTime. This means that if you get a stream with 5 values in the first second and then 10 values in the 3rd second, using Delay with a timespan of 2 seconds will yield results in second 3 and 5. If you use the DateTime overload the values will be yielded with in the first second of the DateTime and then in the 3rd second after the DateTime. This example will delay by 2 seconds and also in one minute.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var inOneMinute = DateTime.Now.AddMinutes(1);
var range = Observable.Range(10, 15);
range.Delay(TimeSpan.FromSeconds(2)).Subscribe(Console.WriteLine);
range.Delay(inOneMinute).Subscribe(Console.WriteLine);&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Sample&amp;lt;T&amp;gt;(TimeSpan)&lt;/strong&gt; will just take a one sample value for every specified TimeSpan and publish that value. Quite simple, quite nice.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var interval = Observable.Interval(TimeSpan.FromMilliseconds(150));
interval.Sample(TimeSpan.FromSeconds(1)).Subscribe(Console.WriteLine);&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Throttle&lt;/strong&gt; is similar to the sample and buffer methods in that it is a time based filter. It is more like sample in that it returns a single value (not an array of values like Buffer). Unlike sample, the window that the values are sampled over is not fixed, it slides every time the underlying stream publishes a value. The throttled stream will only produce a value when the underlying stream does not publish a value for the given period, in which case the last value will be published. When a value is published, the timespan will start and if another value is published the value will only be republished if the timespan has elapsed. Regardless of whether the value is published or not the timespan is reset. This means that if the underlying stream always produces values more frequently than the throttle period then Throttle will never publish any results. &lt;/p&gt;

&lt;p&gt;The most obvious usage of this to me is holding back on sending a &amp;quot;Google suggest&amp;quot; request to the server as a user is still typing. We could throttle the keystrokes so that we only send up the search string when the user pauses for given period.&lt;/p&gt;

&lt;p&gt;In this example all values are ignored as the publisher is producing values quicker than the throttle allows.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var interval = Observable.Interval(TimeSpan.FromMilliseconds(100));
interval.Throttle(TimeSpan.FromMilliseconds(200))
    .Subscribe(Console.WriteLine);&lt;/pre&gt;

&lt;p&gt;This example that varies the rate at which it produces value (emulating sporadic keystrokes), we will get some values written to the console where the delay is more than the throttle period.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;var interval = Observable.Create&amp;lt;&lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;(
    o =&amp;gt;
     {
         &lt;span class="kwrd"&gt;for&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0; i &amp;lt; 100; i++)
         {
             o.OnNext(i);
             Thread.Sleep(i++ % 10 &amp;lt; 5 ? 100 : 300);
         }
         &lt;span class="kwrd"&gt;return&lt;/span&gt; () =&amp;gt; { };
     });
interval.Throttle(TimeSpan.FromMilliseconds(200))
    .Subscribe(Console.WriteLine);&lt;/pre&gt;

&lt;p&gt;In later posts, Buffer is covered in more detail and we expand on more complex time based operators. Also when you introduce concurrency (which these time based operators do) you need to start to understand the Scheduling semantics of Rx which are also covered in later posts.&lt;/p&gt;

&lt;p&gt;Most of these methods are simple and pretty easy to understand. I found my problem with these was the vast number of them. I also appears the the API is less prone to changes in recent releases. If you want to get to know these methods a bit better check out these links, but most importantly – Use them. Have a play in LinqPad or just some console app.&lt;/p&gt;

&lt;p&gt;Useful links:&lt;/p&gt;

&lt;p&gt;&lt;a title="Rx Home" href="http://msdn.microsoft.com/en-us/devlabs/gg577609"&gt;Rx Home&lt;/a&gt;

  &lt;br /&gt;&lt;a title="Exploring the Major Interfaces in Rx - MSDN" href="http://msdn.microsoft.com/en-us/library/hh242974(v=VS.103).aspx"&gt;Exploring the Major Interfaces in Rx&lt;/a&gt; – MSDN

  &lt;br /&gt;&lt;a title="IObservable(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd990377.aspx"&gt;IObservable&amp;lt;T&amp;gt;&lt;/a&gt; interface - MSDN

  &lt;br /&gt;&lt;a title="IObserver(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd783449.aspx"&gt;IObserver&amp;lt;T&amp;gt;&lt;/a&gt; interface - MSDN

  &lt;br /&gt;&lt;a title="Observer Design pattern - MSDN" href="http://msdn.microsoft.com/en-us/library/ee850490.aspx"&gt;Observer Design pattern&lt;/a&gt; - MSDN

  &lt;br /&gt;&lt;a title="ObservableExtensions class - MSDN" href="http://msdn.microsoft.com/en-us/library/system.observableextensions(v=VS.103).aspx"&gt;ObservableExtensions class&lt;/a&gt; - MSDN

  &lt;br /&gt;&lt;a title="Observable static class - MSDN" href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable(v=VS.103).aspx"&gt;Observable class&lt;/a&gt; - MSDN

  &lt;br /&gt;&lt;a title="Observer class - MSDN" href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.observable(v=VS.103).aspx"&gt;Observer class&lt;/a&gt; - MSDN

  &lt;br /&gt;&lt;a title="Qservable class - MSDN" href="http://msdn.microsoft.com/en-us/library/system.reactive.linq.qbservable(v=VS.103).aspx"&gt;Qservable class&lt;/a&gt; - MSDN

  &lt;br /&gt;&lt;a title="Action(Of T) Delegate - MSDN" href="http://msdn.microsoft.com/en-us/library/018hxwa8.aspx"&gt;Action&amp;lt;T&amp;gt;&lt;/a&gt; Delegate - MSDN

  &lt;br /&gt;&lt;a title="Func(Of T1, T2, TResult) - MSDN" href="http://msdn.microsoft.com/en-us/library/bb534647.aspx"&gt;Func&amp;lt;T1, T2, TResult&amp;gt;&lt;/a&gt; - MSDN

  &lt;br /&gt;The Rx Wiki site &lt;a href="http://rxwiki.wikidot.com/101samples"&gt;101 Samples&lt;/a&gt;

  &lt;br /&gt;&lt;a title="Enumerate This - James Miles provides deep dive discussion regarding Linq" href="http://jamesmiles.wordpress.com/"&gt;Enumerate This&lt;/a&gt;

  &lt;br /&gt;&lt;a href="http://www.linqpad.net/"&gt;LinqPad&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The full source code is now available either via svn at &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or as a &lt;a href="http://rx-samples.googlecode.com/files/rx-samples_v008.zip"&gt;zip file&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Back to the &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;contents&lt;/a&gt; page for &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions for .NET Introduction&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Back to the previous post; &lt;a href="http://leecampbell.blogspot.com/2010/05/intro-to-rx.html"&gt;Part 1 - Introduction to Rx&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Forward to next post; &lt;a href="http://leecampbell.blogspot.com/2010/05/rx-part-3-lifetime-management.html"&gt;Part 3 - Lifetime management – Completing and Unsubscribing&lt;/a&gt;&lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:299bbce5-8a1e-4ac0-8d4c-5cc2547a326d" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-1211368060841026290?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/1211368060841026290/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=1211368060841026290' title='7 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/1211368060841026290'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/1211368060841026290'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/05/rx-part-2-static-and-extension-methods.html' title='Rx part 2 – Static and Extension methods'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>7</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-6396000497022215598</id><published>2010-05-18T23:06:00.001+01:00</published><updated>2011-07-02T17:27:54.846+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Rx'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Introduction to Rx Part 1 - Key types</title><content type='html'>&lt;p&gt;Microsoft has released a new library for building “reactive” applications. It’s full name is &lt;a title="Reactive Extensions for .NET" href="http://msdn.microsoft.com/en-us/devlabs/gg577609"&gt;Reactive Extensions for .NET&lt;/a&gt; but is generally referred to as just “Rx”. Essentially Rx is built upon the foundations of the &lt;a href="http://en.wikipedia.org/wiki/Observer_pattern"&gt;Observer&lt;/a&gt; pattern. .NET already exposes some other ways to implement the Observer pattern such as Multicast delegates or Events. Multicast delegates (which Events are) however can be cumbersome to use, have a nasty interface and are difficult to compose and can not be queried. Rx looks to solve these problems.&lt;/p&gt;  &lt;p&gt;Here I will introduce you to the building blocks and some basic types that make up Rx.&lt;/p&gt;  &lt;h4&gt;IObservable&amp;lt;T&amp;gt;&lt;/h4&gt;  &lt;p&gt;&lt;a title="IObservable(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd990377.aspx"&gt;IObservable&amp;lt;T&amp;gt;&lt;/a&gt; is one of the 2 core interfaces for working with Rx. It is a simple interface with just a &lt;a href="http://msdn.microsoft.com/en-us/library/dd782981(v=VS.100).aspx"&gt;Subscribe&lt;/a&gt; method. Microsoft are so confident that this interface will be of use to you it has been included in the BCL as of version 4.0 of .NET. You should be able to think of anything that implements IObservable&amp;lt;T&amp;gt; as a Stream of T objects. So if a method returned an IObservable&amp;lt;Price&amp;gt; I could think of it as a stream of Prices.&lt;/p&gt;  &lt;h4&gt;IObserver&amp;lt;T&amp;gt;&lt;/h4&gt;  &lt;p&gt;&lt;a title="IObserver(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd783449.aspx"&gt;IObserver&amp;lt;T&amp;gt;&lt;/a&gt; is the other one of the 2 core interfaces for working with Rx. It too has made it into the BCL as of .NET 4.0. Don’t worry if you are not on .NET 4.0 yet as the Rx team have included these 2 interfaces in a separate assembly for .NET 3.5 users. IObserver&amp;lt;T&amp;gt; is meant to be the “functional dual of IEnumerable&amp;lt;T&amp;gt;”. If you want to know what that last statement meant then enjoy the hours of videos on &lt;a href="http://channel9.msdn.com/tags/Rx/"&gt;Channel9&lt;/a&gt; where they discuss the mathematical purity of the types. For everyone else it means that where an IEnumerable&amp;lt;T&amp;gt; can effectively yield 3 things (the next value, an exception or the end of the sequence), so too can IObservable&amp;lt;T&amp;gt; via IObserver&amp;lt;T&amp;gt;’s 3 methods OnNext(T), OnError(Exception) and OnCompleted().&lt;/p&gt;  &lt;p&gt;Interestingly, while you will be exposed to the &lt;a title="IObservable(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd990377.aspx"&gt;IObservable&amp;lt;T&amp;gt;&lt;/a&gt; interface a lot if you work with Rx, I find I don't often need to concern myself with &lt;a title="IObserver(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd783449.aspx"&gt;IObserver&amp;lt;T&amp;gt;&lt;/a&gt;. Another interesting thing I have found with Rx is that I never actually implement these interfaces myself, Rx provides all of the implementations I need out of the box. Lets have a look at the simple ones.&lt;/p&gt;  &lt;h4&gt;Subject&amp;lt;T&amp;gt;&lt;/h4&gt;  &lt;p&gt;If you were to create your own implementation of &lt;a title="IObservable(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd990377.aspx"&gt;IObservable&amp;lt;T&amp;gt;&lt;/a&gt; you may find that you need to expose method to publish items to the subscribers, throw errors and notify when the stream is complete. Hmmm they all sound like the methods on the &lt;a title="IObserver(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd783449.aspx"&gt;IObserver&amp;lt;T&amp;gt;&lt;/a&gt; interface. While it may seem odd to have one type implementing both interfaces, it does make life easy. This is what &lt;a title="Using Rx Subjects - MSDN" href="http://msdn.microsoft.com/en-us/library/hh242969(v=VS.103).aspx"&gt;subjects&lt;/a&gt; can do for you.&amp;#160; &lt;a title="Subject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh229173(v=VS.103).aspx"&gt;Subject&amp;lt;T&amp;gt;&lt;/a&gt; is the most basic of the subjects. Effectively you can expose your &lt;a title="Subject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh229173(v=VS.103).aspx"&gt;Subject&amp;lt;T&amp;gt;&lt;/a&gt; behind a method that returns &lt;a title="IObservable(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd990377.aspx"&gt;IObservable&amp;lt;T&amp;gt;&lt;/a&gt; but internally you can use the OnNext, OnError and OnCompleted methods to control the stream.&lt;/p&gt;  &lt;p&gt;In this (awfully basic) example, I create a subject, subscribe to that subject and then publish to the stream.&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.Collections.Generic;

&lt;span class="kwrd"&gt;namespace&lt;/span&gt; RxConsole
{
    &lt;span class="kwrd"&gt;class&lt;/span&gt; Program
    {
        &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
        {
            var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();

            WriteStreamToConsole(subject);

            subject.OnNext(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
            subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
            subject.OnNext(&lt;span class="str"&gt;&amp;quot;c&amp;quot;&lt;/span&gt;);
            Console.ReadKey();
        }

        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; WriteStreamToConsole(IObservable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; stream)
        {
            stream.Subscribe(Console.WriteLine);
        }
    }
}&lt;/pre&gt;

&lt;p&gt;Note that the WriteStreamToConsole method takes an IObservable&amp;lt;string&amp;gt; as it only wants access to the subscribe method. Hang on, doesn’t the Subscribe method need an IObserver&amp;lt;string&amp;gt;? Surely Console.WriteLine does not match that interface. Well not it doesn’t but the Rx team supply me with an Extension Method to &lt;a title="IObservable(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd990377.aspx"&gt;IObservable&amp;lt;T&amp;gt;&lt;/a&gt; that just takes an Action&amp;lt;T&amp;gt;. The action will be executed every time an item is published. There are &lt;a title="ObservableExtensions class - MSDN" href="http://msdn.microsoft.com/en-us/library/system.observableextensions(v=VS.103).aspx"&gt;other overloads to the Subscribe extension method&lt;/a&gt; that allows you to pass combinations of delegates to be invoke for OnNext, OnCompleted and OnError. This effectively means I don't need to implement IObserver&amp;lt;T&amp;gt;. Cool.&lt;/p&gt;

&lt;p&gt;As you can see, &lt;a title="Subject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh229173(v=VS.103).aspx"&gt;Subject&amp;lt;T&amp;gt;&lt;/a&gt; could be quite useful for getting started in Rx programming. &lt;a title="Subject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh229173(v=VS.103).aspx"&gt;Subject&amp;lt;T&amp;gt;&lt;/a&gt; is a basic implementation however. There are 3 siblings to &lt;a title="Subject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh229173(v=VS.103).aspx"&gt;Subject&amp;lt;T&amp;gt;&lt;/a&gt; that offer subtly different implementations which can drastically change the way your program runs.&lt;/p&gt;

&lt;h4&gt;ReplaySubject&amp;lt;T&amp;gt;&lt;/h4&gt;

&lt;p&gt;&lt;a title="ReplaySubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh211810(v=VS.103).aspx"&gt;ReplaySubject&amp;lt;T&amp;gt;&lt;/a&gt; will remember all publications to it so that any subscriptions that happen after publications have been made, will still get all of the publications. Consider this example where we have moved our first publication to occur before our subscription&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
    var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; Subject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();

    subject.OnNext(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
    WriteStreamToConsole(subject);
    
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;c&amp;quot;&lt;/span&gt;);
    Console.ReadKey();
}&lt;/pre&gt;

&lt;p&gt;The result of this would be that “b” and “c” would be written to the console, but “a” ignored. If we were to make the minor change to make subject a &lt;a title="ReplaySubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh211810(v=VS.103).aspx"&gt;ReplaySubject&amp;lt;T&amp;gt;&lt;/a&gt; we would see all publications again.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
    var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; ReplaySubject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();

    subject.OnNext(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
    WriteStreamToConsole(subject);
    
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;c&amp;quot;&lt;/span&gt;);
    Console.ReadKey();
}&lt;/pre&gt;

&lt;p&gt;This can be very handy for eliminating race conditions.&lt;/p&gt;

&lt;h4&gt;BehaviorSubject&amp;lt;T&amp;gt;&lt;/h4&gt;

&lt;p&gt;&lt;a title="BehaviorSubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh211949(v=VS.103).aspx"&gt;BehaviorSubject&amp;lt;T&amp;gt;&lt;/a&gt; is similar to &lt;a title="ReplaySubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh211810(v=VS.103).aspx"&gt;ReplaySubject&amp;lt;T&amp;gt;&lt;/a&gt; except it only remembers the last publication. &lt;a title="BehaviorSubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh211949(v=VS.103).aspx"&gt;BehaviorSubject&amp;lt;T&amp;gt;&lt;/a&gt; also requires you to provide it a default value of T. This means that all subscribers will receive a value immediately (unless it is already completed).&lt;/p&gt;

&lt;p&gt;In this example the value “a” is written to the console.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
    var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; BehaviorSubject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
    WriteStreamToConsole(subject);
    Console.ReadKey();
}&lt;/pre&gt;

&lt;p&gt;In this example the value “b” is written to the console, but not “a”.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
    var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; BehaviorSubject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
    WriteStreamToConsole(subject);
    Console.ReadKey();
}&lt;/pre&gt;

&lt;p&gt;In this example the values “b”, “c” &amp;amp; “d” are all written to the console, but again not “a”&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
    var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; BehaviorSubject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);

    subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
    WriteStreamToConsole(subject);
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;c&amp;quot;&lt;/span&gt;);
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;d&amp;quot;&lt;/span&gt;);
    Console.ReadKey();
}&lt;/pre&gt;

&lt;p&gt;Finally in this example, no values will be published as the stream has completed. Nothing is written to the console.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
    var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; BehaviorSubject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);

    subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;c&amp;quot;&lt;/span&gt;);
    subject.OnCompleted();
    WriteStreamToConsole(subject);
    
    Console.ReadKey();
}&lt;/pre&gt;

&lt;h4&gt;AsyncSubject&amp;lt;T&amp;gt;&lt;/h4&gt;

&lt;p&gt;&lt;a title="AsyncSubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh229363(v=VS.103).aspx"&gt;AsyncSubject&amp;lt;T&amp;gt;&lt;/a&gt; is similar to the Replay and Behavior subjects, however it will only store the last value, and only publish it when the stream is completed. &lt;/p&gt;

&lt;p&gt;In this example no values will be published so no values will be written to the console.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
    var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; AsyncSubject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();

    subject.OnNext(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
    WriteStreamToConsole(subject);
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;c&amp;quot;&lt;/span&gt;);
    Console.ReadKey();
}&lt;/pre&gt;

&lt;p&gt;In this example we invoke the OnCompleted method and the value “c” is published and therefore written to the console.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
{
    var subject = &lt;span class="kwrd"&gt;new&lt;/span&gt; AsyncSubject&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();

    subject.OnNext(&lt;span class="str"&gt;&amp;quot;a&amp;quot;&lt;/span&gt;);
    WriteStreamToConsole(subject);
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;b&amp;quot;&lt;/span&gt;);
    subject.OnNext(&lt;span class="str"&gt;&amp;quot;c&amp;quot;&lt;/span&gt;);
    subject.OnCompleted();
    Console.ReadKey();
}&lt;/pre&gt;

&lt;p&gt;So that is the very basics of Rx. With only that under you belt it may be hard to understand why Rx is a topic of interest. To follow on from this post I will discuss further fundamentals to Rx&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Extension methods &lt;/li&gt;

  &lt;li&gt;Scheduling / Multithreading &lt;/li&gt;

  &lt;li&gt;LINQ syntax &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Once we have covered these it should allow you to really get Rx working for you to produce some tasty Reactive applications. Hopefully after we have covered these background topics we can knock up some Samples where Rx can really help you in your day to day coding.&lt;/p&gt;

&lt;p&gt;The full source code is now available either via svn at &lt;a href="http://code.google.com/p/rx-samples/source/checkout"&gt;http://code.google.com/p/rx-samples/source/checkout&lt;/a&gt; or as a &lt;a href="http://rx-samples.googlecode.com/files/rx-samples_v008.zip"&gt;zip file&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Related links : &lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&lt;a title="IObservable(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd990377.aspx"&gt;IObservable&amp;lt;T&amp;gt;&lt;/a&gt; interface - MSDN 

    &lt;br /&gt;&lt;a title="IObserver(Of T) interface - MSDN" href="http://msdn.microsoft.com/en-us/library/dd783449.aspx"&gt;IObserver&amp;lt;T&amp;gt;&lt;/a&gt; interface - MSDN 

    &lt;br /&gt;&lt;a title="Observer Design pattern - MSDN" href="http://msdn.microsoft.com/en-us/library/ee850490.aspx"&gt;Observer Design pattern&lt;/a&gt; - MSDN 

    &lt;br /&gt;&lt;a title="Rx Home" href="http://msdn.microsoft.com/en-us/devlabs/gg577609"&gt;Rx Home&lt;/a&gt; 

    &lt;br /&gt;&lt;a title="Exploring the Major Interfaces in Rx - MSDN" href="http://msdn.microsoft.com/en-us/library/hh242974(v=VS.103).aspx"&gt;Exploring the Major Interfaces in Rx&lt;/a&gt; – MSDN 

    &lt;br /&gt;&lt;a title="ObservableExtensions class - MSDN" href="http://msdn.microsoft.com/en-us/library/system.observableextensions(v=VS.103).aspx"&gt;ObservableExtensions class&lt;/a&gt; - MSDN 

    &lt;br /&gt;&lt;a title="Using Rx Subjects - MSDN" href="http://msdn.microsoft.com/en-us/library/hh242969(v=VS.103).aspx"&gt;Using Rx Subjects&lt;/a&gt; - MSDN 

    &lt;br /&gt;&lt;a title="System.Reactive.Subjects Namespace - MSDN" href="http://msdn.microsoft.com/en-us/library/system.reactive.subjects(v=VS.103).aspx"&gt;System.Reactive.Subjects Namespace&lt;/a&gt; - MSDN 

    &lt;br /&gt;&lt;a title="Subject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh229173(v=VS.103).aspx"&gt;Subject&amp;lt;T&amp;gt;&lt;/a&gt; - MSDN 

    &lt;br /&gt;&lt;a title="AsyncSubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh229363(v=VS.103).aspx"&gt;AsyncSubject&amp;lt;T&amp;gt;&lt;/a&gt; - MSDN 

    &lt;br /&gt;&lt;a title="BehaviorSubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh211949(v=VS.103).aspx"&gt;BehaviorSubject&amp;lt;T&amp;gt;&lt;/a&gt; - MSDN 

    &lt;br /&gt;&lt;a title="ReplaySubject(Of T) - MSDN" href="http://msdn.microsoft.com/en-us/library/hh211810(v=VS.103).aspx"&gt;ReplaySubject&amp;lt;T&amp;gt;&lt;/a&gt; - MSDN 

    &lt;br /&gt;&lt;a title="Subject static class - MSDN" href="http://msdn.microsoft.com/en-us/library/system.reactive.subjects.subject(v=VS.103).aspx"&gt;Subject static class&lt;/a&gt; - MSDN 

    &lt;br /&gt;&lt;a title="ISubject(Of TSource, TResult)" href="http://msdn.microsoft.com/en-us/library/hh229572(v=VS.103).aspx"&gt;ISubject&amp;lt;TSource, TResult&amp;gt;&lt;/a&gt; - MSDN 

    &lt;br /&gt;&lt;a title="ISubject(Of T)" href="http://msdn.microsoft.com/en-us/library/hh211669(v=VS.103).aspx"&gt;ISubject&amp;lt;T&amp;gt;&lt;/a&gt; - MSDN&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Back to the &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;contents&lt;/a&gt; page for &lt;a href="http://leecampbell.blogspot.com/2010/08/reactive-extensions-for-net.html"&gt;Reactive Extensions for .NET Introduction&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Forward to next post; &lt;a href="http://leecampbell.blogspot.com/2010/05/rx-part-2-static-and-extension-methods.html"&gt;Part 2 - Static and extension methods&lt;/a&gt; &lt;/p&gt;

&lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:be38a79c-9817-441f-8e0f-6b14e3552b3f" class="wlWriterEditableSmartContent"&gt;Technorati Tags: &lt;a href="http://technorati.com/tags/Reactive-Extensions" rel="tag"&gt;Reactive-Extensions&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Rx" rel="tag"&gt;Rx&lt;/a&gt;,&lt;a href="http://technorati.com/tags/Tutorial" rel="tag"&gt;Tutorial&lt;/a&gt;&lt;/div&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-6396000497022215598?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/6396000497022215598/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=6396000497022215598' title='10 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/6396000497022215598'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/6396000497022215598'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/05/intro-to-rx.html' title='Introduction to Rx Part 1 - Key types'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>10</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-2181308935053482494</id><published>2010-05-12T19:14:00.001+01:00</published><updated>2010-08-28T18:17:03.451+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><title type='text'>MergedDictionaries performance problems in WPF</title><content type='html'>&lt;p&gt;I don’t normally like to blatantly plagiarise other people’s comments, but this seems to be a little know bug that sounds like it should be shared.&lt;/p&gt;  &lt;p&gt;A colleague of mine emailed our internal tech list the following email&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;b&gt;I strongly urge everyone working with WPF to use this or at least benchmark it in your own applications if you use ResourceDictionaries.MergedDictionaries. I consider this to be a huge problem in WPF. I’m not sure if it exists in Silverlight, but I would assume it does.&lt;/b&gt;&lt;/p&gt;    &lt;p&gt;I was just debugging a very long render delay in some WPF code and I came across this little tidbit:&lt;/p&gt;    &lt;p&gt;&lt;a href="http://webcache.googleusercontent.com/search?q=cache:J-0cI6EgRJcJ:www.wpftutorial.net/MergedDictionaryPerformance.html+mergeddictionaries+shared&amp;amp;cd=4&amp;amp;hl=en&amp;amp;ct=clnk&amp;amp;gl=us&amp;amp;client=firefox-a"&gt;&lt;/a&gt;&lt;a href="http://www.wpftutorial.net/MergedDictionaryPerformance.html"&gt;http://www.wpftutorial.net/MergedDictionaryPerformance.html&lt;/a&gt;&lt;/a&gt;&lt;/p&gt;    &lt;p&gt;The quote of interest is: “Each time a control references a &lt;code&gt;ResourceDictionary&lt;/code&gt; XAML creates a new instance of it. So if you have a custom control library with 30 controls in it and each control references a common dictionary you create 30 identical resource dictionaries!”&lt;/p&gt;    &lt;p&gt;Normally that isn’t a huge problem, but when you consider the way that I personally (and have suggested to others) that they organize their resources in Prism projects it gets to be a &lt;b&gt;**serious**&lt;/b&gt; problem. For example, let’s say we have this project structure:&lt;/p&gt;    &lt;pre&gt;/MyProject.Resources
       /Resources
                -Buttons.xaml
                -DataGrid.xaml
                -Global.xaml
                -Brushes.xaml
                -WindowChrome.xaml
                -Icons.xaml
 
/MyProject.Module1
      /Resources
                -Module1Resources.xaml  (References all Dictionaries in /MyProject.Resources/Resources/*)
      /Views
                -View1.xaml
                -View2.xaml
      
/MyProject.Module2
      /Resources
                -Module2Resources.xaml   (References all Dictionaries in /MyProject.Resources/Resources/*)
      /Views
                -View1.xaml
                -View2.xaml
      
/MyProject.Shell
      /Resources
                -ShellResources.xaml   
      /Views
                -MainShell.xaml&lt;/pre&gt;

  &lt;p&gt;If in your views you reference the module-level ResourceDictionary (which helps for maintainability and modularity) then every time you create an instance of View1.xaml for example, you &lt;b&gt;would have to parse all the ResourceDictionaries in /MyProject.Resources/Resources/* every time. &lt;/b&gt;This isn’t really a memory concern but it is a huge performance concern. There can potentially be thousands of lines of XAML code to parse and the time really does add up.&lt;/p&gt;

  &lt;p&gt;I recently switched all of the MergedDictionary references:&lt;/p&gt;

  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ResourceDictionary&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ResourceDictionary.MergedDictionaries&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ResourceDictionary&lt;/span&gt; &lt;span class="attr"&gt;Source&lt;/span&gt;=”/&lt;span class="attr"&gt;SomeDictionary&lt;/span&gt;.&lt;span class="attr"&gt;xaml&lt;/span&gt;” &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;ResourceDictionary.MergedDictionaries&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;ResourceDictionary&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;p&gt;To use the attached SharedResourceDictionary which &lt;b&gt;shadows the Source property and keeps a global cache of all ResourceDictionaries parsed&lt;/b&gt;:&lt;/p&gt;

  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ResourceDictionary&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ResourceDictionary.MergedDictionaries&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;SharedResourceDictionary&lt;/span&gt; &lt;span class="attr"&gt;Source&lt;/span&gt;=”/&lt;span class="attr"&gt;SomeDictionary&lt;/span&gt;.&lt;span class="attr"&gt;xaml&lt;/span&gt;” &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;ResourceDictionary.MergedDictionaries&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;ResourceDictionary&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

  &lt;p&gt;And I saw a &lt;b&gt;performance increase of almost two orders of magnitude … From almost 6000ms to 200ms. &lt;/b&gt;I’ve attached this code; I used the basic sample implementation in the link above so this is considered public information for client purposes.&lt;/p&gt;

  &lt;p&gt;Cheers,&lt;/p&gt;

  &lt;p&gt;Charlie&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Thanks to Charlie Robbins (&lt;a title="Lab49 - Innovation on demand" href="http://www.lab49.com/"&gt;Lab49&lt;/a&gt;) for expanding on Christian’s blog post and for letting me re-print your email.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-2181308935053482494?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/2181308935053482494/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=2181308935053482494' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/2181308935053482494'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/2181308935053482494'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/05/mergeddictionaries-performance-problems.html' title='MergedDictionaries performance problems in WPF'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-7057790982831080181</id><published>2010-02-13T01:25:00.001Z</published><updated>2010-08-28T18:17:32.805+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Chart'/><title type='text'>Squeezing out performance from Charting</title><content type='html'>&lt;p&gt;After my review of the charting products available currently I decided to go with the Slverlight/WPF Data Visualization project (from the WPF Toolkit). I did end up coming up with a trick to squeeze some performance out of the charts. Quite simply that charts don’t handle a lot of data very well. When you have rich data templates, animation and more than several hundred data points, performance is pretty poor. I decided that the first thing to compromise on would be animation. It is nice but I would rather speed. By turning off the animation in the charting I get a little speed up but there still is a simple truth that must be considered. If my graph is only 500px wide then why try to render more than 500 data points? This is my first step to gaining some performance; filter out data by sampling so we never try to get the chart to render more data than it ever could.&lt;/p&gt;  &lt;p&gt;I can achieve this by creating a custom CollectionViewSource. The new sub class is simple; &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;it has a dependency property of MaxItemCount &lt;/li&gt;    &lt;li&gt;on any change to the MaxItemCount or the Source we sample the data set, and save the values we want to display into a set &lt;/li&gt;    &lt;li&gt;we subscribe to the Filter event and only accept an item if it is included in our sample set &lt;/li&gt; &lt;/ul&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; CollectionSizeFilter : CollectionViewSource
{
    &lt;span class="kwrd"&gt;int&lt;/span&gt; _count;
    ICollectionView _defaultView;
    HashSet&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt; _toKeep;

    &lt;span class="kwrd"&gt;public&lt;/span&gt; CollectionSizeFilter()
    {
        Filter += CollectionSizeFilter_Filter;
    }

    &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;virtual&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; CollectionSizeFilter_Filter(&lt;span class="kwrd"&gt;object&lt;/span&gt; sender, FilterEventArgs e)
    {
        e.Accepted = _toKeep == &lt;span class="kwrd"&gt;null&lt;/span&gt; || _toKeep.Contains(e.Item);
    }

    &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; OnSourceChanged(&lt;span class="kwrd"&gt;object&lt;/span&gt; oldSource, &lt;span class="kwrd"&gt;object&lt;/span&gt; newSource)
    {
        &lt;span class="kwrd"&gt;base&lt;/span&gt;.OnSourceChanged(oldSource, newSource);
        _defaultView = GetDefaultView(newSource);
        _count = Count(_defaultView.SourceCollection);

        LoadHashset();
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;double&lt;/span&gt; MaxItemCount
    {
        get { &lt;span class="kwrd"&gt;return&lt;/span&gt; (&lt;span class="kwrd"&gt;double&lt;/span&gt;)GetValue(MaxItemCountProperty); }
        set { SetValue(MaxItemCountProperty, &lt;span class="kwrd"&gt;value&lt;/span&gt;); }
    }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; DependencyProperty MaxItemCountProperty = DependencyProperty.Register(&lt;span class="str"&gt;&amp;quot;MaxItemCount&amp;quot;&lt;/span&gt;, &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(&lt;span class="kwrd"&gt;double&lt;/span&gt;), &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(CollectionSizeFilter), &lt;span class="kwrd"&gt;new&lt;/span&gt; UIPropertyMetadata(1d, MaxItemCountProperty_Changed));

    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; MaxItemCountProperty_Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var self = (CollectionSizeFilter)sender;
        self.LoadHashset();
    }

    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; LoadHashset()
    {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (_count &amp;lt;= MaxItemCount)
        {
            _toKeep = &lt;span class="kwrd"&gt;null&lt;/span&gt;;
        }
        &lt;span class="kwrd"&gt;else&lt;/span&gt;
        {
            _toKeep = &lt;span class="kwrd"&gt;new&lt;/span&gt; HashSet&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt;();
            var gap = MaxItemCount - 1;
            var spacing = _count / gap;
            &lt;span class="kwrd"&gt;double&lt;/span&gt; nextIndex = 0d;
            &lt;span class="kwrd"&gt;int&lt;/span&gt; i = 0;
            &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var item &lt;span class="kwrd"&gt;in&lt;/span&gt; _defaultView.SourceCollection)
            {
                &lt;span class="kwrd"&gt;if&lt;/span&gt; (i &amp;gt;= nextIndex)
                {
                    _toKeep.Add(item);
                    nextIndex += spacing;
                }
                i++;
            }
        }
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (View != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
            View.Refresh();
    }

    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Count(IEnumerable source)
    {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (source == &lt;span class="kwrd"&gt;null&lt;/span&gt;)
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; 0;
        }
        var is2 = source &lt;span class="kwrd"&gt;as&lt;/span&gt; ICollection;
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (is2 != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; is2.Count;
        }
        &lt;span class="kwrd"&gt;int&lt;/span&gt; num = 0;
        IEnumerator enumerator = source.GetEnumerator();
        {
            &lt;span class="kwrd"&gt;while&lt;/span&gt; (enumerator.MoveNext())
            {
                num++;
            }
        }
        &lt;span class="kwrd"&gt;return&lt;/span&gt; num;
    }
}&lt;/pre&gt;

&lt;p&gt;To use the new “control” we just treat it like a normal CollectionViewSource but we specifiy the MaxItemCount by binding it to the width of the Chart like this.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Controls:CollectionSizeFilter&lt;/span&gt; &lt;span class="attr"&gt;x:Key&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;FilteredData&amp;quot;&lt;/span&gt; 
    &lt;span class="attr"&gt;Source&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding MyData}&amp;quot;&lt;/span&gt; 
    &lt;span class="attr"&gt;MaxItemCount&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding ElementName=chart1, Path=ActualWidth}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;This gave some performance improvements but I thought why not follow this concept down the path a little bit more. For most data that&amp;#160; I want to display I am mainly interested in the trend not the minutia. So why do I try to show a data point on every pixel? I could just sample the data; for example if I have a data set of 1500 data points and a graph that is 500px wide, I get some performance gains by reducing the rendered data set to 500 data points, but why not just show one data point every say 10px? If this is acceptable for your data then you can reduce your rendered data set from 1500 down to 50 (30 times less data to render). To do this is even more simple than the code above. We just need to create and implementation of IValueConverter to do some division, a DivisionConverter.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;sealed&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; DivisionConverter : IValueConverter
{
    &lt;span class="preproc"&gt;#region&lt;/span&gt; IValueConverter Members
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; Convert(&lt;span class="kwrd"&gt;object&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt;, Type targetType, &lt;span class="kwrd"&gt;object&lt;/span&gt; parameter, CultureInfo culture)
    {
        &lt;span class="kwrd"&gt;double&lt;/span&gt; numerator = ConvertToDouble(&lt;span class="kwrd"&gt;value&lt;/span&gt;, culture);
        &lt;span class="kwrd"&gt;double&lt;/span&gt; denominator = ConvertToDouble(parameter, culture);
        &lt;span class="kwrd"&gt;return&lt;/span&gt; numerator / denominator;
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; ConvertBack(&lt;span class="kwrd"&gt;object&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt;, Type targetType, &lt;span class="kwrd"&gt;object&lt;/span&gt; parameter, CultureInfo culture)
    {
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; NotImplementedException();
    }
    &lt;span class="preproc"&gt;#endregion&lt;/span&gt;

    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;double&lt;/span&gt; ConvertToDouble(&lt;span class="kwrd"&gt;object&lt;/span&gt; &lt;span class="kwrd"&gt;value&lt;/span&gt;, IFormatProvider culture)
    {
        var result = &lt;span class="kwrd"&gt;default&lt;/span&gt;(&lt;span class="kwrd"&gt;double&lt;/span&gt;);
        &lt;span class="kwrd"&gt;try&lt;/span&gt;
        {
            var source = &lt;span class="kwrd"&gt;value&lt;/span&gt; &lt;span class="kwrd"&gt;as&lt;/span&gt; IConvertible;
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (source != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
                result = source.ToDouble(culture);
        }
        &lt;span class="kwrd"&gt;catch&lt;/span&gt;
        {
        }
        &lt;span class="kwrd"&gt;return&lt;/span&gt; result;
    }
}&lt;/pre&gt;

&lt;p&gt;So now we can just extend our previous XAML to include the new converter and apply our sample size of 10.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Controls:DivisionConverter&lt;/span&gt; &lt;span class="attr"&gt;x:Key&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;divisionConverter&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Controls:CollectionSizeFilter&lt;/span&gt; &lt;span class="attr"&gt;x:Key&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;FilteredData&amp;quot;&lt;/span&gt; 
    &lt;span class="attr"&gt;Source&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding MyData}&amp;quot;&lt;/span&gt;
    &lt;span class="attr"&gt;MaxItemCount&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding ElementName=chart1, Path=ActualWidth, 
        Converter={StaticResource divisionConverter}, 
        ConverterParameter=10}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Putting it all together I end up with code like below. I prefer to keep my concerns near each other, so here I have defined the filters in the LineSeries Resources instead of where some may put them which is the top of the file. I would however define the key to the DivisionConverter at the top of the file or even in the App.xaml as I will probably use it in many places. Note how I use RelativeSource Binding to find the width of the parent chart.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;chartingToolkit:Chart&lt;/span&gt; &lt;span class="attr"&gt;Name&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;chart1&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;chartingToolkit:LineSeries&lt;/span&gt; 
        &lt;span class="attr"&gt;Title&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding Title}&amp;quot;&lt;/span&gt;
        &lt;span class="attr"&gt;DependentValuePath&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Value&amp;quot;&lt;/span&gt;
        &lt;span class="attr"&gt;IndependentValuePath&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Date&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;chartingToolkit:LineSeries.Resources&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Controls:CollectionSizeFilter&lt;/span&gt; 
                &lt;span class="attr"&gt;x:Key&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;FilteredBalances&amp;quot;&lt;/span&gt; 
                &lt;span class="attr"&gt;Source&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding Balances}&amp;quot;&lt;/span&gt;
                &lt;span class="attr"&gt;MaxItemCount&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding 
                        RelativeSource={RelativeSource FindAncestor, 
                        AncestorType={x:Type chartingToolkit:Chart}}, 
                        Path=ActualWidth,
                        Converter={StaticResource DivisionConverter}, 
                        ConverterParameter=10}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;chartingToolkit:LineSeries.Resources&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;chartingToolkit:LineSeries.ItemsSource&lt;/span&gt; &lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Binding&lt;/span&gt; &lt;span class="attr"&gt;Source&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{StaticResource FilteredBalances}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;chartingToolkit:LineSeries.ItemsSource&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;chartingToolkit:LineSeries&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;chartingToolkit:Chart&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;You may find your millage varies with the sampling size. You may be only comfortable with small values like 3-5 or you may be more aggressive with values around 30. It is your data and you will know what is best for you. The real beauty of this is that problem of performance is a presentation problem. With some simple controls we are able to tame the problem in the presentation layer without having to compromise the purity of our ViewModels (like setting max size values that get sent to databases). Here if we resize the chart, we already have all the data so we just render more data points. Also the solution is very generic, there are no dependencies on the WPF Data Visualization assemblies so you may find other uses for them.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-7057790982831080181?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/7057790982831080181/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=7057790982831080181' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7057790982831080181'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7057790982831080181'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/02/squeezing-out-performance-from-charting.html' title='Squeezing out performance from Charting'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-6751338548287131405</id><published>2010-01-18T07:09:00.002Z</published><updated>2010-08-28T18:17:50.407+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Chart'/><title type='text'>My WPF Charting Comparisons</title><content type='html'>&lt;p&gt;I have recently been looking for some graphing/charting functionality for a home project I am working on. My requirements are fairly simple:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;handle data quantities in the region of thousands and tens of thousands of rows/items &lt;/li&gt;    &lt;li&gt;be able to display line charts with or without data points (there will be so many data points that they can become noise) &lt;/li&gt;    &lt;li&gt;be able to display multiple sets of data to be able to compare data &lt;/li&gt;    &lt;li&gt;free or cheap &lt;/li&gt;    &lt;li&gt;xcopy install &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Now as the Charting products I wanted to compare were all going to be in WPF I assumed that these requirements were just a given but apparently not, so let me specify them as well&lt;/p&gt;  &lt;ol style="counter-rest: item 5" start="6"&gt;   &lt;li&gt;be able to bind the data from my own view model (i.e. I don’t want to have controls littering my View Model) &lt;/li&gt;    &lt;li&gt;have the graph update as the data changes &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Now to see the list of contenders:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a href="http://wpf.codeplex.com/" target="_blank"&gt;WPF Toolkit Charting&lt;/a&gt; (aka System.Windows.Controls.DataVisualization.Toolkit) &lt;/li&gt;    &lt;li&gt;&lt;a href="http://wpf.amcharts.com" target="_blank"&gt;AmCharts&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://visifire.com/" target="_blank"&gt;VisiFire&lt;/a&gt; &lt;/li&gt;    &lt;li&gt;&lt;a href="http://dynamicdatadisplay.codeplex.com" target="_blank"&gt;DynamicDataDisplay&lt;/a&gt; (aka D3) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;So for the really quick review of each&lt;/p&gt;  &lt;h4&gt;WPF Toolkit Charting&lt;/h4&gt;  &lt;p&gt;This is the CodePlex project from some of the lads at Microsoft. This is presumable of a lesser quality than the rest of the Toolkit as the Charting component is in preview. The WPF Toolkit allows for great looking charts by utilising the power of WPF Styles. It is one of those balancing acts that must be difficult to make when designing software; extensibility vs. simplicity. The WPF Toolkit leans more towards the extensible option. Extending the charts to look the way you want can be done but many will find it fiddly and frustrating, but once done can be very rewarding and the Graphs can look amazing. The WPF Toolkit also utilises the power of WPF binding by allowing me to bind to my ViewModel. So it looks like a good start, however, the clear and painful problem with the WPF Toolkit is performance. When loading up even hundreds of rows/items the performance is fairly poor. When I tried to throw just over a thousand items at a Line Series the performance was completely unacceptable. One other problem I have is that I get intermittent lock ups. When updating the data, the charting code will run off into a loop and not come out of it, freezing the UI. Hmmm another cross.&lt;/p&gt;  &lt;p&gt;Positives:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Extensibility allows for beautiful graphs &lt;/li&gt;    &lt;li&gt;Charts bind to ViewModel &lt;/li&gt;    &lt;li&gt;Free &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Negatives:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Woeful performance &lt;/li&gt;    &lt;li&gt;Random lock ups. &lt;/li&gt; &lt;/ul&gt;  &lt;h4&gt;AmCharts&lt;/h4&gt;  &lt;p&gt;AmCharts appears to be a Charting solution aimed at the financial industry. The chart control that I thought would best fit my needs was the Stock chart. This chart had a great feature that allowed zooming on the X-axis by providing a range slider. Performance was great when I threw ~1500 items at the control. An odd problem I had was the graph would only appear once I resized my window. I think this has to do with binding to a ViewModel as the Demo does not have this problem but it also directly interacts with the control from the Code behind. I want to avoid “messing with controls” from my ViewModel. A more real problem I have is that while the performance is great, the binding seems to be a once off event. Changes to the values in my collection are not reflected by any change to the chart.&lt;/p&gt;  &lt;p&gt;Positives&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Good performance &lt;/li&gt;    &lt;li&gt;Charts bind to ViewModel &lt;/li&gt;    &lt;li&gt;Zoom functionality &lt;/li&gt;    &lt;li&gt;Good samples &lt;/li&gt;    &lt;li&gt;Smallest DLL size (223KB)&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Negatives&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;One time data binding &lt;/li&gt;    &lt;li&gt;Odd problem with Chart not rendering until i resized the window. &lt;/li&gt; &lt;/ul&gt;  &lt;h4&gt;Visifire&lt;/h4&gt;  &lt;p&gt;VisiFire charts looked to be a great option. They were very easy to get up and running, had some good samples like the AmCharts. My first play with the Visifire charts provided me with a good looking chart. My problems came when I went to bind the Charts to my ViewModel…Visifire does not support data binding! I’m not even sure why someone would write a WPF control that does not support data binding. I wasted plenty off time writing some adapters so that I could get data binding working. Data binding is in the wish list for version 3 (how it didn't make it into the wish list for the 1st version I don’t know). Performance of Visfire was pretty good (not spectacular) and sat in between AmCharts and the hopelessly slow WPF Toolkit.&lt;/p&gt;  &lt;p&gt;Positives&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Easy to get up and running &lt;/li&gt;    &lt;li&gt;Pretty good looking default charts &lt;/li&gt;    &lt;li&gt;Moderate performance &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Negatives&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;You cant bind a data series to a collection! &lt;/li&gt; &lt;/ul&gt;  &lt;h4&gt;Dynamic Data Display&lt;/h4&gt;  &lt;p&gt;The Dynamic Data Display (aka D3) is another Microsoft project on Codeplex from a Microsoft research team in Russia. D3 authors claim outstanding performance even with massive amounts of data. Sounds like a sure fire winner! The control library also supports different types of charts to the other libraries like Maps and Isolines ( I have no idea what an isoline is). The samples show some good stuff with smooth moving animated graphs with dynamic data points. The big fail on the project is again, no data binding. All manipulation of the charts needs to be done in C# code and needs to be very imperative. There are some guys, however, who have made posts creating an extension to the controls to support data-binding. Either way, while this looked to be a good set of controls, the authors don’t appear to have followed the &lt;a href="http://blogs.msdn.com/brada/archive/2005/10/07/478375.aspx" target="_blank"&gt;Pit-of-Success&lt;/a&gt; principle. I would go in to details, but the fact it took me hours of reading forums, looking at samples and coding to just get my Model showing on the screen. When it did get on to the screen it was fast, but didn’t update when the underlying data changed. This is a very immature set of controls but may have a bright future if the team can get some fundamentals right.&lt;/p&gt;  &lt;p&gt;Positives&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;High performance &lt;/li&gt;    &lt;li&gt;Easy to scroll and zoom data &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Negatives&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Hardest set of controls to work with. Everything has to be done in code. Authors seem to miss the point of WPF entirely. Presentation and logic feel very much couple together. &lt;/li&gt;    &lt;li&gt;After all my mucking around the chart didn’t update with my changes to the data. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;In summary, I am pretty disappointed with the state of all of these charting controls. What I did manage to get working to a satisfactory state was the WPF Toolkit. As the only real problem I had with the WPF Toolkit charting controls was their performance; I decided that an easy way to get some better performance out of the control was to only show as many data points as there were available pixels. If I only have 400 pixels to show my data it becomes a bit silly to try and get the graph to render 1400 data points. I created a Custom Control that extends CollectionViewSource by having a MaxItemCount property that can be set to effectively filter the amount of data the CollectionViewSource reveals to the Charting controls. The performance was better but I was able to further tweak the performance by adding a DivisionConverter to further reduce the collection size by the parameter specified (10 in my case). This means I only show a data point for every 10 pixels wide the chart is. This ended up being a great compromise….except for the random lock ups. If I play on the Chart for long enough changing the data to update the chart, eventually the program just falls in to a loop. If I can solve this bug I may have a winner on my hands. &lt;em&gt;Ed:—Playing around more I may have got rid of this problem. Still pops up sometimes straight after a build, but a restart fixes it. This may be to do with my build of Win7 (pre release that I am still running). This throws the WPF Toolkit +the 2 tiny bits of filter code clearly into the lead as it can be made to look great and handle tens of thousands of rows.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;If any one is interested in the code I used to test/play with each of these libraries you can find a zip of the VS2008 solution &lt;a title="ChartingPlaygournd.zip" href="http://cid-76a2ea424cb9f9ae.skydrive.live.com/self.aspx/Blog/Charting/ChartingPlayground.zip" target="_blank"&gt;here&lt;/a&gt;. To see any of the spikes, just set it as the start up project and run or Right click on the project and “Debug”—&amp;gt; “Start new instance”. Only the MyDomain project wont run as that is the Class library that has the small part of the domain to test the charts with.&lt;/p&gt;  &lt;p&gt;&lt;a title="ChartingPlayground.zip" href="http://cid-76a2ea424cb9f9ae.skydrive.live.com/self.aspx/Blog/Charting/ChartingPlayground.zip" target="_blank"&gt;ChartingPlaygournd.zip – Source code for my tests.&lt;/a&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-6751338548287131405?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/6751338548287131405/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=6751338548287131405' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/6751338548287131405'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/6751338548287131405'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2010/01/my-wpf-charting-comparisons.html' title='My WPF Charting Comparisons'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-165238024491206603</id><published>2009-09-23T00:05:00.001+01:00</published><updated>2009-09-23T00:05:27.923+01:00</updated><title type='text'>Logging in modern .NET applications</title><content type='html'>&lt;h3&gt;Background - A common evolution to logging &lt;/h3&gt; Recently we needed to implement a decent logging solution for a new application. The application (like so many) had evolved from a proof of concept (P.O.C) code base. 5 weeks after the cut over from P.O.C to code that was intended to ship, we had a plethora of &lt;em&gt;Debug.WriteLine&lt;/em&gt;, &lt;em&gt;Console.WriteLine&lt;/em&gt; and &lt;em&gt;Trace.WriteLine&lt;/em&gt;s sprinkled through the code base. Most of the *.WriteLine code was to help debug  &lt;ol&gt;   &lt;li&gt;code that implemented 3rd party code &lt;/li&gt;    &lt;li&gt;code that had no tests (booo!) and F5 testing seemed to be &amp;quot;good enough&amp;quot;&lt;/li&gt; &lt;/ol&gt; After a couple of preliminary builds were sent to the client for initial evaluation, several un-handled exceptions had crept through. To be fair to the team, most of these were related to some undocumented features of the 3rd party system and few were my fault where maybe I was pushing WPF a bit to far for the clients machines. The result of these exceptions were a custom popup window on the WPF application, stating that a fatal exception had occurred and would shut down now. We would also email the exception as a quick way to notify the dev team of any errors.  &lt;br /&gt;At this point in time the team had decided we had several real problems here:  &lt;ol&gt;   &lt;li&gt;We had various &amp;quot;debugging&amp;quot; systems (Console, debug and trace) &lt;/li&gt;    &lt;li&gt;We had hard coded our implementations of &amp;quot;logging&amp;quot;. If logging a specific piece of functionality is a requirement we really should test that we are logging the correct thing! &lt;/li&gt;    &lt;li&gt;As the WPF guy I am interested in any WPF binding errors (in the VS output window), but the service/agent guy were flooding the console screen with their pub/sub debug messages. How could I filter out their messages, and how could they filter out mine? &lt;/li&gt;    &lt;li&gt;We were catching the un-handled exception at the dispatcher, not at the point it was thrown. This mean we had a huge stack trace (noise) pointing back to the problem and we also were missing some useful data to debug the exception such as the inputs to the method that threw the exception.&lt;/li&gt; &lt;/ol&gt;  &lt;h3&gt;Setting the requirements&lt;/h3&gt; From the problems we have above the team decided that our requirements for the logging system were:  &lt;ul&gt;   &lt;li&gt;Testable &lt;/li&gt;    &lt;li&gt;Provide different levels(severity) of logging. Trace, Debug and Exception. &lt;/li&gt;    &lt;li&gt;Filter on logging level &lt;/li&gt;    &lt;li&gt;Log to various targets. Email, File and Console. &lt;/li&gt;    &lt;li&gt;Provide different areas or categories to log as. e.g. Presentation, Agent, Services...&lt;/li&gt;    &lt;li&gt;Filter on logging Category (so I don't see the agent debug messages and agent developers don't see my presentation guff)&lt;/li&gt; &lt;/ul&gt; The requirements for the implementation of the logging system are:  &lt;ul&gt;   &lt;li&gt;Log un-handled exceptions so we can analyse then when they occur on live &lt;/li&gt;    &lt;li&gt;Log the inputs to the method that threw the exception so we can identify it it is data related &lt;/li&gt;    &lt;li&gt;Replace console/debug/trace calls with new logger.&lt;/li&gt; &lt;/ul&gt;  &lt;h3&gt;Journey to a solution&lt;/h3&gt;  &lt;h4&gt;Logging System&lt;/h4&gt; First thing I will tackle is the testability. I will create my own interface called ILogger that will do my logging for me  &lt;br /&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; ILogger
{
  &lt;span class="kwrd"&gt;void&lt;/span&gt; Write(&lt;span class="kwrd"&gt;string&lt;/span&gt; message);
}&lt;/pre&gt;

&lt;br /&gt;Well that was easy! Next, Provide different levels of logging. I am going to do that by replacing my Write method with level specific methods:

&lt;br /&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; ILogger
{
    &lt;span class="kwrd"&gt;void&lt;/span&gt; Trace(&lt;span class="kwrd"&gt;string&lt;/span&gt; message);
    &lt;span class="kwrd"&gt;void&lt;/span&gt; Debug(&lt;span class="kwrd"&gt;string&lt;/span&gt; message);
    &lt;span class="kwrd"&gt;void&lt;/span&gt; Error(&lt;span class="kwrd"&gt;string&lt;/span&gt; message);
}&lt;/pre&gt;

&lt;p&gt;To now add Categories. Here I will add a category parameter to each of the methods. I would advise against using enums for your categories, especially if your logger becomes a shared API. Enums can not be extended and really tie you down.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; ILogger
{
    &lt;span class="kwrd"&gt;void&lt;/span&gt; Trace(&lt;span class="kwrd"&gt;string&lt;/span&gt; category, &lt;span class="kwrd"&gt;string&lt;/span&gt; message);
    &lt;span class="kwrd"&gt;void&lt;/span&gt; Debug(&lt;span class="kwrd"&gt;string&lt;/span&gt; category, &lt;span class="kwrd"&gt;string&lt;/span&gt; message);
    &lt;span class="kwrd"&gt;void&lt;/span&gt; Error(&lt;span class="kwrd"&gt;string&lt;/span&gt; category, &lt;span class="kwrd"&gt;string&lt;/span&gt; message);
}&lt;/pre&gt;

&lt;p&gt;Hmmm. It now looks like the write we are making a mess for the poor developer who has to implement this interface. I think I may have been on the right track with the write method in the first place. I am going to change that back a Write method that takes 3 parameters. I will offer extension methods to give users the ability to make calls like the one above (a little bit more work for me but less work for everyone else). See &lt;a title="How not to write Interfaces - includes explanation on how to use extension methods with interfaces" href="http://leecampbell.blogspot.com/2009/08/how-not-to-write-interface-in-c-30.html" target="_blank"&gt;here&lt;/a&gt; for more info on extending interfaces with Extension methods.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; ILogger
{
    &lt;span class="kwrd"&gt;void&lt;/span&gt; Write(LogLevel level, &lt;span class="kwrd"&gt;string&lt;/span&gt; category, &lt;span class="kwrd"&gt;string&lt;/span&gt; message);
}&lt;/pre&gt;

&lt;p&gt;Some may be thinking that &amp;quot;Hang on. Strings are bad! Surely a category Enum has to be better?&amp;quot;. To answer this I would recommend using an internal class like this &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;class&lt;/span&gt; Category
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Agent = &lt;span class="str"&gt;&amp;quot;Agent&amp;quot;&lt;/span&gt;;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Presentation = &lt;span class="str"&gt;&amp;quot;Presentation&amp;quot;&lt;/span&gt;;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;const&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Agent = &lt;span class="str"&gt;&amp;quot;Service&amp;quot;&lt;/span&gt;;
}&lt;/pre&gt;

&lt;p&gt;If you want to expose categories at your public API, create a public version of this class that consumers can use an even inherit from to add their own categories too. If you are thinking &amp;quot;shouldnt they be public static readonly?&amp;quot;, I will cover that later.
  &lt;br /&gt;Checking off aginst our requirements list we can cross somethings off&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strike&gt;Testable &lt;/strike&gt;(Interfaces make things testable)&lt;/li&gt;

  &lt;li&gt;&lt;strike&gt;Provide different levels(severity) of logging. Trace, Debug and Exception.&lt;/strike&gt;&lt;/li&gt;

  &lt;li&gt;Filter on logging level &lt;/li&gt;

  &lt;li&gt;Log to various targets. Email, File and Console. &lt;/li&gt;

  &lt;li&gt;&lt;strike&gt;Provide different areas or categories to log as. eg Presentation, Agent, Services...&lt;/strike&gt;&lt;/li&gt;

  &lt;li&gt;Filter on logging Category (so I dont see the agent debug messages and agent developers don't see my presentation guff)&lt;/li&gt;
&lt;/ul&gt;
So that is a good start. Now we need to add filtering and targeting various outputs. Well luckily there are plenty of 3rd party logging tools out there that do all of this for us. As our project is using Enterprise Library already we will just use their logging application block. Look to the example at the end of the post for complete example.

&lt;br /&gt;Great! Thanks to the 3rd party logging system we have ticked off all of our system requirements, now for our implementation requirements.

&lt;h4&gt;Implementation of Logging&lt;/h4&gt;
Now that we have an interface to code against, let us now look at how we would use it.

&lt;br /&gt;&lt;i&gt;Ed- This is completely back to front. You should normally look at how you would use it first and then create the implementation. TDD is a great methodology for this. We are approaching it back-to-front in this post because I think it is easier to consume for the reader.&lt;/i&gt;

&lt;br /&gt;So the main pain point we have is logging exceptions that occur at the agents (the classes that get data from services and map them to client side entities). This is due to poor 3rd party documentation, Live being slightly different to Dev and QA and integration testing being harder to perform than unit testing. 

&lt;br /&gt;Prior to our new Logging system some agent code might look like this:

&lt;br /&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; AmendPortfolio(PortfolioAmmendment portfolio)
{
    Console.WriteLine(&lt;span class="str"&gt;&amp;quot;AmendPortfolio {0}&amp;quot;&lt;/span&gt;, portfolio.Id);
    var data = portfolio.MapToServiceData();    &lt;span class="rem"&gt;//Mapper extension method.&lt;/span&gt;
    _service.AmendBasket(_session, data, &lt;span class="kwrd"&gt;true&lt;/span&gt;);    &lt;span class="rem"&gt;//Call to 3rd party system&lt;/span&gt;
    Console.WriteLine(&lt;span class="str"&gt;&amp;quot;AmendPortfolio complete&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;

&lt;br /&gt;Now if we swapped out the console calls with out logger and then put in some exception logging it may look like this

&lt;br /&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; AmendPortfolio(PortfolioAmmendment portfolio)
{
    _logger.Debug(Category.Agent, &lt;span class="str"&gt;&amp;quot;AmendPortfolio {0}&amp;quot;&lt;/span&gt;, portfolio.Id);
    &lt;span class="kwrd"&gt;try&lt;/span&gt;
    {
        var data = portfolio.MapToServiceData();    &lt;span class="rem"&gt;//Mapper extension method.&lt;/span&gt;
        _service.AmendBasket(_session, data, &lt;span class="kwrd"&gt;true&lt;/span&gt;);    &lt;span class="rem"&gt;//Call to 3rd party system&lt;/span&gt;
    }
    &lt;span class="kwrd"&gt;catch&lt;/span&gt;(Exception ex)
    {
        _logger.Error(Category.Agent, ex.ToString);
        &lt;span class="kwrd"&gt;throw&lt;/span&gt;;
    }
    _logger.Debug(Category.Agent, &lt;span class="str"&gt;&amp;quot;AmendPortfolio complete&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;

&lt;br /&gt;Oh dear. We now have more code that does logging than code that does real work. While we have satisfied our requirements, we have doubled our work load. Not good. Back to the drawing board.

&lt;h4&gt;AOP&lt;/h4&gt;
Some will have heard of Aspect Orientated Programming. It seemed like 5 years ago it was going to change everything. Well it mainly just changed logging. AOP is a style of programming that allows code to be injected at a given interception point. In our case the interception point would be the start of our agent method, the end of the agent method and when the method throws and exception (which is really the same as the end of the method). As far as I know there are 2 popular ways to achieve this

&lt;ol&gt;
  &lt;li&gt;at run time using a tool like Castle Windsor or Microsoft Unity &lt;/li&gt;

  &lt;li&gt;at compile time using a tool like PostSharp&lt;/li&gt;
&lt;/ol&gt;
I have had some experience with PostSharp as I used it prior to Unity having the ability to add interceptors. So for our solution we went with PostSharp. I believe to switch between any of these options would not be a huge amount of work.

&lt;br /&gt;First a quick introduction on how I have previously done AOP logging with PostSharp. I would create an Attribute that I would apply to classes or methods that I wanted to be logged. The attribute would satisfy the requirements of PostSharp so that code would be injected at compile time to do my logging.

&lt;br /&gt;code like this 

&lt;br /&gt;

&lt;pre class="csharpcode"&gt;[Logged]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; AmendPortfolio(PortfolioAmmendment portfolio)
{
    var data = portfolio.MapToServiceData();    &lt;span class="rem"&gt;//Mapper extension method.&lt;/span&gt;
    _service.AmendBasket(_session, data, &lt;span class="kwrd"&gt;true&lt;/span&gt;);    &lt;span class="rem"&gt;//Call to 3rd party system&lt;/span&gt;
}&lt;/pre&gt;

&lt;br /&gt;which at compile time would alter the IL to represent something more like this:

&lt;br /&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; AmendPortfolio(PortfolioAmmendment portfolio)
{
    Logger.Debug(&lt;span class="str"&gt;&amp;quot;AmendPortfolio({0})&amp;quot;&lt;/span&gt;, portfolio.Id);
    &lt;span class="kwrd"&gt;try&lt;/span&gt;
    {
        var data = portfolio.MapToServiceData();    &lt;span class="rem"&gt;//Mapper extension method.&lt;/span&gt;
        _service.AmendBasket(_session, data, &lt;span class="kwrd"&gt;true&lt;/span&gt;);    &lt;span class="rem"&gt;//Call to 3rd party system&lt;/span&gt;
    }
    &lt;span class="kwrd"&gt;catch&lt;/span&gt;(Exception ex)
    {
        Logger.Error(ex.ToString);
        &lt;span class="kwrd"&gt;throw&lt;/span&gt;;
    }
    Logger.Debug(&lt;span class="str"&gt;&amp;quot;AmendPortfolio complete&amp;quot;&lt;/span&gt;);
}&lt;/pre&gt;
Well that looks perfect doesn't it? Not really. We dont have a category specified and we have a hard coded reference the static class Logger from Enterprise Library Logging. It no longer points to our _logger member variable which was of type ILogger. This makes our testing harder to do. If testing your logger is not really something you care about (which is fine) then this AOP solution might be for you. If you do want to be more specific about logging then we need to find a way of getting hold of the instance of ILogger. As PostSharp is a compile time AOP framework, it is a touch harder to integrate than if we used Unity or Windsor. The main problem is how do we get a handle on the Logger? A solution we came up with was to create an ILogged interface

&lt;br /&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; ILogged
{
    ILogger Logger { get; }
}&lt;/pre&gt;
By doing this we expose the Logger so we can use it in the Aspect/Attribute. Now if we look at out method that we are trying to log in the greater context of the class it resides in we can see what the implementation may now look like.

&lt;br /&gt;

&lt;pre class="csharpcode"&gt;[Logged]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; PortfolioAgent : IPortfolioAgent, ILogged
{
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; ILogger _logger;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; ISomeService _service;
    &lt;span class="kwrd"&gt;public&lt;/span&gt; PortfolioAgent(ILogger logger, ISomeService _service)
    {
        _logger = logger;
        _service = service;
    }
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; AmendPortfolio(PortfolioAmmendment portfolio)
    {
        var data = portfolio.MapToServiceData();    &lt;span class="rem"&gt;//Mapper extension method.&lt;/span&gt;
        _service.AmendBasket(_session, data, &lt;span class="kwrd"&gt;true&lt;/span&gt;);    &lt;span class="rem"&gt;//Call to 3rd party system&lt;/span&gt;
    }
}&lt;/pre&gt;

&lt;br /&gt;That looks kinda cool to me. One thing my colleagues made a note of is that they would prefer if in this scenario we used property injection for the logger. This is fine with me as long as it is easy to use and we can still test it. The ILogged interface does not preclude using property injection, it is just not my preference. Another thing to note is the lack of Category. Easy fix there is to add a property to our LoggedAttribute of string Category.

&lt;br /&gt;

&lt;pre class="csharpcode"&gt;[Logged(Category=Category.Agent)]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; PortfolioAgent : IPortfolioAgent, ILogged
{
...
}&lt;/pre&gt;

&lt;p&gt;
  &lt;br /&gt;If you remember earlier that I mentioned &lt;em&gt;public const&lt;/em&gt; vs &lt;em&gt;public static readonly&lt;/em&gt;. This is the reason why I choose to use const types so that they could be used in the attribute.&lt;/p&gt;

&lt;p&gt;
  &lt;br /&gt;I am pretty happy with this now. I think we tick off all of our requirements and have not added a lot of complexity to our code. The one last thing that bugs me is that I have to use the LoggedAttribute and the ILogged interface as a couple. If I forget to use one without the other, I either will get no logging, a nasty runtime exception or if I code a aspect correctly I can get a compile time error (the most desirable). At first I coded the attribute to do the latter (compile time error), but then realised that all of my agents were in one project and all used the same Category. To make life a little bit easier I moved the attribute to the AssemblyInfo and had the Aspect apply itself automatically to any class the implemented ILogged. This maybe a step too far towards black magic for some teams, so do what fits best.&lt;/p&gt;

&lt;p&gt;Have a look at the &lt;a title="Logging with DI and AOP in C# demo code" href="http://dl.getdropbox.com/u/895810/blog/ArtemisWest.Demos.Logging.zip" target="_blank"&gt;sample code here&lt;/a&gt;. Both styles are shown in the example so take your pick of which suits you best.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-165238024491206603?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/165238024491206603/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=165238024491206603' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/165238024491206603'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/165238024491206603'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2009/09/logging-in-modern-net-applications.html' title='Logging in modern .NET applications'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-73993792287215416</id><published>2009-09-16T15:49:00.001+01:00</published><updated>2009-09-18T11:56:47.347+01:00</updated><title type='text'>Success, Motivation and Management</title><content type='html'>&lt;p&gt;I just watched an interesting presentation from Dan Pink on &lt;a title="Dan Pink on the surprising science of motivation" href="http://www.ted.com/talks/dan_pink_on_motivation.html" target="_blank"&gt;The surprising science of motivation&lt;/a&gt;. Here he discusses the conventional ways to get productivity out of employees via carrot and stick mentality. Watch the video first (18min) so I don't take the wind from his sails.&lt;/p&gt;  &lt;p&gt;What I found interesting especially on refection of my earlier post &lt;a title="Projects &amp;#8211; Measuring success and providing boundaries" href="http://leecampbell.blogspot.com/2008/08/projects-measuring-success-and.html" target="_blank"&gt;Projects &amp;#8211; Measuring success and providing boundaries&lt;/a&gt;, was how he related the 20th century management style to prescriptive roles. Prescriptive roles are roles where you can give very clear guidance on how to perform a task and boundaries of the role. Boundaries normally define measurable tasks with reward/punishment (carrot/stick) attached to the tasks. These can anything from simple things such as &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;If you work late the company will pay for pizza delivery &lt;/li&gt;    &lt;li&gt;if the project comes in on time you get a bonus &lt;/li&gt;    &lt;li&gt;if you meet your &lt;a title="Key Performance Indicator" href="http://en.wikipedia.org/wiki/Key_performance_indicator" target="_blank"&gt;KPI&lt;/a&gt;s you get all of your bonus. Pessimistically viewed as: miss any of your &lt;a title="Key Performance Indicator" href="http://en.wikipedia.org/wiki/Key_performance_indicator" target="_blank"&gt;KPI&lt;/a&gt;s and we will dock your pay. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;However the interesting thing about prescriptive roles is that in the 21st century the game has changed. Any task that can be completed without a level of creativity, abstract thought or reasoning generally can be done:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;cheaper by outsourced labour &lt;/li&gt;    &lt;li&gt;faster by automation (mechanical or computer) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;This affects the software industry massively. Outsourcing burst on to the scene at the turn of the century and appeared to be the Holy Grail for accountants across western civilisation. This also scared the hell out of any &amp;quot;computer guy&amp;quot; as how was he going to make the payments on his new sports car? Outsourcing was not all that is was cracked up to be with stories of low quality product and communication failures. Outsourcing seems to be making a small come back and I think that we will see this see-saw rock a little bit more before outsourcing becomes part of our day to day life. See the &lt;a title="The 4 hour working week - Tim Ferriss" href="http://www.fourhourworkweek.com/" target="_blank"&gt;4 hour working week&lt;/a&gt; for some great ideas on outsourcing your life.&lt;/p&gt;  &lt;p&gt;Dan Pink discusses that the 20th Century style of carrot/stick management worked well with prescriptive roles. But we are in the 21st century now and I would like to think that any one reading this is not performing a prescriptive role. I would even argue that our role is to eliminate or automate what we can. Normally these things that can be eliminated or automated are prescriptive processes. Roles that add real value to any company &lt;strong&gt;do&lt;/strong&gt; require creativity, problem solving, communication skills, building relationships etc. These things cannot (yet) be automated.&lt;/p&gt;  &lt;p&gt;So moving from the production line 20th century to the service orientated 21st century we are seeing a shift from the role of management being one based around compliance (carrot/stick) to self managing, autonomous teams/employees. This is in line with what agile and lean concepts are trying to achieve. Creating a culture where&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;autonomy &lt;/li&gt;    &lt;li&gt;mastery &lt;/li&gt;    &lt;li&gt;purpose &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;are values that are held dear, creates an amazing shift positivity of the team. Instead prescribing exactly what is to be done and creating a drone army (which could be replaced by outsourcing or automation), try setting clear expectations of the outcomes you want achieved and let the team go for it. This will give the team a sense of worth as you are touching on &lt;a title="Maslow&amp;#39;s Hierarchy of Needs" href="http://en.wikipedia.org/wiki/Maslow%27s_hierarchy_of_needs" target="_blank"&gt;Maslow's Hierarchy of Needs&lt;/a&gt; by giving them a channel for creativity and problem solving, but probably more importantly a sense of respect and belonging. Obviously it doesn't have to be a free-for-all, which would no doubt result in total failure, but simple things like burn down charts, daily stand-up's can give 'management' visibility of progress.&lt;/p&gt;  &lt;h4&gt;So what can you do if you are not management?&lt;/h4&gt;  &lt;p&gt;I believe that people are attracted to like people. If you value and exercise principles like mastery, purpose, independence, interdependence then I think you will attract to companies where that is the culture. Easiest thing to do is trying for mastery. In the information age it is simple to learn new skills. &lt;strong&gt;Simple is not the same as Easy&lt;/strong&gt; however. Finding the information on a subject is not the same as mastering it, so you have to jump in feet first and make mistakes. Ideally this is not on mission critical projects. I do a lot of mini projects at home to learn a new skill. Some companies like Google are now offering time at work to do this stuff. If your company does not offer this time, then you may want to consider your priorities and see if you can make time for self development. 30 minutes on the way to work, you can read 10 pages of a book. That should allow you around 1 book per month. If you drive/cycle to work, then maybe audio books or podcasts are for you. This is only one part of the path to mastery. You then need to distil the information you are collecting. At the end of a chapter, jot down some notes in your own words of what you just learnt. The act of distilling the information will help you understand it better. To further improve your understanding, actually do something that requires your new skill. Lastly to really see if you understand the skill, try teaching someone else the skill. This really shows you where you are weak still.&lt;/p&gt;  &lt;p&gt;Next, start automating the prescriptive parts of your role. For C# guys this mainly done for us with tools like automated build servers and Resharper. If have not worn out our tab key then as a C# code you probably don't use snippets/live templates enough. If you don't have a little keyboard short cut for getting latest, building, running tests and checking in then automate it! If part of your role can't be automated, try outsourcing it. It is amazing what people will do if you ask them nicely - &amp;quot;Excuse me Tony you don't mind taking this mail to the mail room for me?&amp;quot;&lt;/p&gt;  &lt;p&gt;Once you are on the track for mastery by creating some sort of self development routine*, you have automated or outsourced the prescriptive parts to your role, you can now concentrate on delivering value from your role. This is where purpose comes in. Ideally as you develop more skills, reduce drone work and start delivering more value from your role management may feel that you can have a level of autonomy. From their perspective giving you autonomy now is really just reducing their work load. If you constantly deliver value, management will naturally move away from &lt;em&gt;compliance management&lt;/em&gt; to &lt;em&gt;engagement.&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href="http://www.projectsmart.co.uk/smart-goals.html" target="_blank"&gt;S.M.A.R.T. goals&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a title="Projects &amp;#8211; Measuring success and providing boundaries" href="http://leecampbell.blogspot.com/2008/08/projects-measuring-success-and.html" target="_blank"&gt;Projects &amp;#8211; Measuring success and providing boundaries&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;*I try to read a minimum one book per month. I also try to keep up with my blog subscriptions but constantly have hundreds of unread post. As a guide apparently Bill Gates reads 3 books a weekend!&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-73993792287215416?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/73993792287215416/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=73993792287215416' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/73993792287215416'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/73993792287215416'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2009/09/success-motivation-and-management.html' title='Success, Motivation and Management'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-5941973729379465295</id><published>2009-08-14T23:05:00.001+01:00</published><updated>2010-08-28T18:22:21.750+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Code Quality'/><category scheme='http://www.blogger.com/atom/ns#' term='patterns'/><title type='text'>How not to write an Interface in C# 3.0</title><content type='html'>&lt;p&gt;While working with the IUnityContainer interface from Microsoft's Patterns and Practices team, I decided that it was well worth a post on how &lt;b&gt;not &lt;/b&gt;to design interfaces. Recent discussion amongst &lt;a title="Explicit Interfaces - Ramblings from Rhys" href="http://rhysc.blogspot.com/2009/08/explicit-interfaces.html" target="_blank"&gt;Rhys&lt;/a&gt; and &lt;a title="Why interfaces - AbstractCode" href="http://abstractcode.com/abstractblog/archive/2009/07/09/173.aspx" target="_blank"&gt;Colin&lt;/a&gt; (&lt;a title="On the granularity of services - AbstractCode" href="http://abstractcode.com/abstractblog/archive/2009/08/12/183.aspx" target="_blank"&gt;here as well&lt;/a&gt;) have been interesting but I imagine most would agree that both arguments are probably fighting over which polish to use on their code. If these are the big battles you have to face at work then I am jealous. &lt;/p&gt;  &lt;p&gt;Introducing IUnityContainer ....   &lt;br /&gt;42 members are defined on this interface. &lt;strong&gt;Fail.&lt;/strong&gt;    &lt;br /&gt;With much restraint I wont go on about it and flame the guys who write it. Most people know of my disdain for the P&amp;amp;P team at Microsoft. So what tips do I give to make this a usable again? Lets break down the solution into a few tips:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Extension methods &lt;/li&gt;    &lt;li&gt;Cohesion &lt;/li&gt;    &lt;li&gt;Intention revealing interfaces&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;How do each of these help us. Let look at some code I was writing pre-extension methods. It was a validation interface that had 2 methods, Validate and Demand&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IValidator&amp;lt;T&amp;gt;
{
  IEnumerable&amp;lt;ValidationErrors&amp;gt; Validate(T item);

  &lt;span class="rem"&gt;///&amp;lt;exception cref=&amp;quot;ValidationException&amp;quot;&amp;gt;Thrown when the item is not valid&amp;lt;/exception&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;void&lt;/span&gt; Demand(T item);
}&lt;/pre&gt;

&lt;p&gt;The problem with this interface is that all implementations of the interface would/could implement Demand the same way; Make a call to Validate(T item) and if any ValidationErrors came back throw an exception with the validation failures. Time ticks by and I realise the now that I have extension methods in C# 3.0 (.NET 3.5). I only need to have the Validate method on my interface now and provide the Demand implementation as an extension method. The code now becomes:
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IValidation&amp;lt;T&amp;gt;
{
  &lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// Validates the specified item, returning a collection of validation errors.&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;param name=&amp;quot;item&amp;quot;&amp;gt;The item to validate.&amp;lt;/param&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;returns&amp;gt;Returns a &amp;lt;see cref=&amp;quot;T:ArtemisWest.ValidationErrorCollection&amp;quot;/&amp;gt; that is empty for a valid item, &lt;/span&gt;
  &lt;span class="rem"&gt;/// or contains the validation errors if the item is not in a valid state.&amp;lt;/returns&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;remarks&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// Implementations of &amp;lt;see cref=&amp;quot;T:ArtemisWest.IValidation`1&amp;quot;/&amp;gt; should never return null from the validate method.&lt;/span&gt;
  &lt;span class="rem"&gt;/// If no validation errors occured then return an empty collection.&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;/remarks&amp;gt;&lt;/span&gt;
  IEnumerable&amp;lt;ValidationErrors&amp;gt; Validate(T item);
}
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; ValidatorExtensions
{
  &lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// Raises a &amp;lt;see cref=&amp;quot;T:ArtemisWest.ValidationException&amp;quot;/&amp;gt; if the &amp;lt;paramref name=&amp;quot;item&amp;quot;/&amp;gt; is not valid.&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;typeparam name=&amp;quot;T&amp;quot;&amp;gt;The type that the instance of &amp;lt;see cref=&amp;quot;T:IValidation`1&amp;quot;/&amp;gt; targets.&amp;lt;/typeparam&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;param name=&amp;quot;validator&amp;quot;&amp;gt;The validator.&amp;lt;/param&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;param name=&amp;quot;item&amp;quot;&amp;gt;The item to be validated.&amp;lt;/param&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;exception cref=&amp;quot;T:ArtemisWest.ValidationException&amp;quot;&amp;gt;&lt;/span&gt;
  &lt;span class="rem"&gt;/// Thrown when validating the &amp;lt;paramref name=&amp;quot;item&amp;quot;/&amp;gt; returns any errors. Only the first &lt;/span&gt;
  &lt;span class="rem"&gt;/// validation error is raised with the exception. Any validation errors that are marked as&lt;/span&gt;
  &lt;span class="rem"&gt;/// warnings are ignored.&lt;/span&gt;
  &lt;span class="rem"&gt;/// &amp;lt;/exception&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Demand&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IValidation&amp;lt;T&amp;gt; validator, T item)
  {
    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var error &lt;span class="kwrd"&gt;in&lt;/span&gt; validator.Validate(item))
    {
      &lt;span class="kwrd"&gt;if&lt;/span&gt; (!error.IsWarning)
      {
        &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ValidationException(error);
      }
    }
  }
}&lt;/pre&gt;

&lt;p&gt;Then end result is that the API feels the same as I have access to both methods, but the cost of implementing my interface is reduced to just its core concern.
  &lt;br /&gt;So, extension methods is one trick we have in the bag. Next cohesion. &lt;/p&gt;

&lt;p&gt;The recent discussion between Rhys and Colin is &amp;quot;how many members belong on an interface?&amp;quot; I think both will agree that answer is not 42. Juval Lowy made a great presentation at TechEd2008 on Interfaces and that we should be aiming for 3-7 members per interface. This provides us with a level of cohesion and a low level of coupling. Lets look at some of the members on the IUnityContainer Interface.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;8 overloads of RegisterInstance &lt;/li&gt;

  &lt;li&gt;16 overloads of RegisterType &lt;/li&gt;

  &lt;li&gt;Add/Remove &amp;quot;Extensions&amp;quot; methods &lt;/li&gt;

  &lt;li&gt;4 overloads of BuildUp &lt;/li&gt;

  &lt;li&gt;2 overloads of ConfigureContainer &lt;/li&gt;

  &lt;li&gt;CreateChildContainer &lt;/li&gt;

  &lt;li&gt;4 overloads of Resolve &lt;/li&gt;

  &lt;li&gt;2 overloads of ResolveAll &lt;/li&gt;

  &lt;li&gt;A TearDown method &lt;/li&gt;

  &lt;li&gt;and a Parent property&lt;/li&gt;
&lt;/ul&gt;
Whew! Well how can we tame this beast? When I look at this interface I see certain groups that look like they are related in usage. They would be the 

&lt;ol&gt;
  &lt;li&gt;Register and Resolve functionality&lt;/li&gt;

  &lt;li&gt;And and Remove extensions functionality &lt;/li&gt;

  &lt;li&gt;Build up and teardown functionality &lt;/li&gt;

  &lt;li&gt;Container hierarchy functionality (Parent and CreateChildContainer) &lt;/li&gt;

  &lt;li&gt;Container configuration&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
  &lt;br /&gt;&lt;i&gt;Interestingly on our current project we only use the Register/Resolve functionality.&lt;/i&gt;

  &lt;br /&gt;These five groups to me have some level of cohesion. That to me then makes them a candidate for there own interfaces. The big giveaway being that I use unity quite successfully but never use 4/5 of the functionality defined on this interface. So our 2nd tip would be to split out these groups on functionality into there own interfaces.

  &lt;br /&gt;But what do we name the new interfaces? This is our 3rd tip: &lt;/p&gt;

&lt;p&gt;&lt;em&gt;Intention revealing interfaces. &lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Looking at my list I would imagine some useful names could be:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;IContainer &lt;/li&gt;

  &lt;li&gt;IExtensionContainer &lt;/li&gt;

  &lt;li&gt;ILifecycleContainer &lt;/li&gt;

  &lt;li&gt;INestedContainer &lt;/li&gt;

  &lt;li&gt;IConfigurableContainer&lt;/li&gt;
&lt;/ol&gt;
To be honest, I have put little thought into these names. Normally I would put a LOT of effort into getting the naming right, but I don't work on the P&amp;amp;P team so these changes will never be done so why waste my time? &lt;em&gt;Edit: My laziness here really does take the wind our of the sails of this argument. Sorry.&lt;/em&gt;

&lt;br /&gt;Ok so how can we bring this all together? My proposal would be to have 6 interfaces

&lt;ol&gt;
  &lt;li&gt;IContainer &lt;/li&gt;

  &lt;li&gt;IExtensionContainer &lt;/li&gt;

  &lt;li&gt;ILifecycleContainer &lt;/li&gt;

  &lt;li&gt;INestedContainer &lt;/li&gt;

  &lt;li&gt;IConfigurableContainer &lt;/li&gt;

  &lt;li&gt;IUnityContainer : IContainer, IExtensionContainer, ILifecycleContainer, INestedContainer, IConfigurableContainer&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
  &lt;br /&gt;Next I would create some extension methods to deal with the silly amount of duplication the multiple overloads incur. Looking at the implementation in UnityContainerBase I would think that all of these methods could be candidates for extension methods&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; UnityContainerBase : IUnityContainer, IDisposable
{
  &lt;span class="rem"&gt;//prior code removed for brevity&lt;/span&gt;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IUnityContainer RegisterInstance&amp;lt;TInterface&amp;gt;(TInterface instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IUnityContainer RegisterInstance&amp;lt;TInterface&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt; name, TInterface instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), name, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IUnityContainer RegisterInstance&amp;lt;TInterface&amp;gt;(TInterface instance, LifetimeManager lifetimeManager)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, lifetimeManager);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IUnityContainer RegisterInstance(Type t, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.RegisterInstance(t, &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IUnityContainer RegisterInstance&amp;lt;TInterface&amp;gt;(&lt;span class="kwrd"&gt;string&lt;/span&gt; name, TInterface instance, LifetimeManager lifetimeManager)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), name, instance, lifetimeManager);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IUnityContainer RegisterInstance(Type t, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance, LifetimeManager lifetimeManager)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.RegisterInstance(t, &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, lifetimeManager);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IUnityContainer RegisterInstance(Type t, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.RegisterInstance(t, name, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
  &lt;span class="rem"&gt;//Remaining code removed for brevity&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;all of these methods just delegate to the one method overload left as abstract&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;abstract&lt;/span&gt; IUnityContainer RegisterInstance(
    Type t, 
    &lt;span class="kwrd"&gt;string&lt;/span&gt; name, 
    &lt;span class="kwrd"&gt;object&lt;/span&gt; instance, 
    LifetimeManager lifetime);&lt;/pre&gt;

&lt;p&gt;The obvious thing to do here is to just make all of these extension methods in the same namespace as the interfaces&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; IContainerExtensions
{
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IContainer RegisterInstance&amp;lt;TInterface&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IContainer container, TInterface instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IContainer RegisterInstance&amp;lt;TInterface&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IContainer container, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, TInterface instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), name, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IContainer RegisterInstance&amp;lt;TInterface&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IContainer container, TInterface instance, LifetimeManager lifetimeManager)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, lifetimeManager);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IContainer RegisterInstance(&lt;span class="kwrd"&gt;this&lt;/span&gt; IContainer container, Type t, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(t, &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IContainer RegisterInstance&amp;lt;TInterface&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IContainer container, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, TInterface instance, LifetimeManager lifetimeManager)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), name, instance, lifetimeManager);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IContainer RegisterInstance(&lt;span class="kwrd"&gt;this&lt;/span&gt; IContainer container, Type t, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance, LifetimeManager lifetimeManager)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(t, &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, lifetimeManager);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IContainer RegisterInstance(&lt;span class="kwrd"&gt;this&lt;/span&gt; IContainer container, Type t, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(t, name, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
}&lt;/pre&gt;

&lt;p&gt;This now reduces our IContainer Interface to just the one method&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IContainer
{
  IContainer RegisterInstance(Type t, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance, LifetimeManager lifetime);
}&lt;/pre&gt;

&lt;p&gt;
  &lt;br /&gt;One thing to note here is that we have broken the contract because we now return IContainer not IUnityContainer. We will come back to this problem later.

  &lt;br /&gt;If we then follow suit on the other interfaces we have created, we will have 6 interfaces that look like this:

  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IContainer
{
  IContainer RegisterType(Type from, Type to, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, LifetimeManager lifetimeManager, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers);
  IContainer RegisterInstance(Type t, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance, LifetimeManager lifetime);
  &lt;span class="kwrd"&gt;object&lt;/span&gt; Resolve(Type t, &lt;span class="kwrd"&gt;string&lt;/span&gt; name);
  IEnumerable&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt; ResolveAll(Type t);
}
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IExtensionContainer
{
  IExtensionContainer AddExtension(UnityContainerExtension extension);
  IExtensionContainer RemoveAllExtensions();
}
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; ILifecycleContainer
{
  &lt;span class="kwrd"&gt;object&lt;/span&gt; BuildUp(Type t, &lt;span class="kwrd"&gt;object&lt;/span&gt; existing, &lt;span class="kwrd"&gt;string&lt;/span&gt; name);
  &lt;span class="kwrd"&gt;void&lt;/span&gt; Teardown(&lt;span class="kwrd"&gt;object&lt;/span&gt; o);
}
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; INestedContainer
{
  INestedContainer CreateChildContainer();
  INestedContainer Parent { get; }
}
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IConfigurableContainer
{
  &lt;span class="kwrd"&gt;object&lt;/span&gt; Configure(Type configurationInterface);
}
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IUnityContainer : IDisposable, IContainer, IExtensionContainer, ILifecycleContainer, INestedContainer, IConfigurableContainer
{}&lt;/pre&gt;

&lt;p&gt;So now we have some much more managable interfaces to work with. However, we have broken the feature that it had before of returning IUnityContainer from each method. You may ask why would you return the instance when clearly you already have the instance? By doing so you can create a fluent interface. See my other post on &lt;a href="http://leecampbell.blogspot.com/2008/11/method-chaining-to-create-your-dsl.html" target="_blank"&gt;Fluent interfaces&lt;/a&gt; and &lt;a href="http://leecampbell.blogspot.com/2008/11/how-c-30-helps-you-with-creating-dsl.html" target="_blank"&gt;DSLs&lt;/a&gt; for more information.

  &lt;br /&gt;Now that we have removed all the noise from the interfaces we actually have a reasonable number of members to work with. This makes me think that maybe we can refactor back to a single interface? Lets have a look:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IUnityContainer : IDisposable
{
  IUnityContainer RegisterType(Type from, Type to, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, LifetimeManager lifetimeManager, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers);
  IUnityContainer RegisterInstance(Type t, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance, LifetimeManager lifetime);
  &lt;span class="kwrd"&gt;object&lt;/span&gt; Resolve(Type t, &lt;span class="kwrd"&gt;string&lt;/span&gt; name);
  IEnumerable&amp;lt;&lt;span class="kwrd"&gt;object&lt;/span&gt;&amp;gt; ResolveAll(Type t);
  IUnityContainer AddExtension(UnityContainerExtension extension);
  IUnityContainer RemoveAllExtensions();
  &lt;span class="kwrd"&gt;object&lt;/span&gt; BuildUp(Type t, &lt;span class="kwrd"&gt;object&lt;/span&gt; existing, &lt;span class="kwrd"&gt;string&lt;/span&gt; name);
  &lt;span class="kwrd"&gt;void&lt;/span&gt; Teardown(&lt;span class="kwrd"&gt;object&lt;/span&gt; o);
  IUnityContainer Parent { get; }
  IUnityContainer CreateChildContainer();
  &lt;span class="kwrd"&gt;object&lt;/span&gt; Configure(Type configurationInterface);
}&lt;/pre&gt;

&lt;p&gt;Well that is 13 members, which is above my happy limit of 10 and nearly double my ideal limit of 7, however...I think this would be a vast improvement on the silly interface that currently exists with its 42 members.
  &lt;br /&gt;Just for fun here are the Extension methods that would complete the interface to bring it back to feature complete.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; IUnityContainerExtentions
{
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer AddNewExtension&amp;lt;TExtension&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container) &lt;span class="kwrd"&gt;where&lt;/span&gt; TExtension : UnityContainerExtension, &lt;span class="kwrd"&gt;new&lt;/span&gt;()
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.AddExtension(Activator.CreateInstance&amp;lt;TExtension&amp;gt;());
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; T BuildUp&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, T existing)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; (T)container.BuildUp(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(T), existing, &lt;span class="kwrd"&gt;null&lt;/span&gt;);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; BuildUp(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type t, &lt;span class="kwrd"&gt;object&lt;/span&gt; existing)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.BuildUp(t, existing, &lt;span class="kwrd"&gt;null&lt;/span&gt;);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; T BuildUp&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, T existing, &lt;span class="kwrd"&gt;string&lt;/span&gt; name)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; (T)container.BuildUp(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(T), existing, name);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; TConfigurator Configure&amp;lt;TConfigurator&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container) &lt;span class="kwrd"&gt;where&lt;/span&gt; TConfigurator : IUnityContainerExtensionConfigurator
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; (TConfigurator)container.Configure(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TConfigurator));
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterInstance&amp;lt;TInterface&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, TInterface instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterInstance&amp;lt;TInterface&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, TInterface instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), name, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterInstance&amp;lt;TInterface&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, TInterface instance, LifetimeManager lifetimeManager)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, lifetimeManager);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterInstance(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type t, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(t, &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterInstance&amp;lt;TInterface&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, TInterface instance, LifetimeManager lifetimeManager)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TInterface), name, instance, lifetimeManager);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterInstance(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type t, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance, LifetimeManager lifetimeManager)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(t, &lt;span class="kwrd"&gt;null&lt;/span&gt;, instance, lifetimeManager);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterInstance(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type t, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;object&lt;/span&gt; instance)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterInstance(t, name, instance, &lt;span class="kwrd"&gt;new&lt;/span&gt; ContainerControlledLifetimeManager());
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(T), &lt;span class="kwrd"&gt;null&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt;, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType&amp;lt;TFrom, TTo&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers) &lt;span class="kwrd"&gt;where&lt;/span&gt; TTo : TFrom
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TFrom), &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TTo), &lt;span class="kwrd"&gt;null&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt;, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, LifetimeManager lifetimeManager, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(T), &lt;span class="kwrd"&gt;null&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt;, lifetimeManager, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType&amp;lt;TFrom, TTo&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, LifetimeManager lifetimeManager, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers) &lt;span class="kwrd"&gt;where&lt;/span&gt; TTo : TFrom
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TFrom), &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TTo), &lt;span class="kwrd"&gt;null&lt;/span&gt;, lifetimeManager, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(T), &lt;span class="kwrd"&gt;null&lt;/span&gt;, name, &lt;span class="kwrd"&gt;null&lt;/span&gt;, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType&amp;lt;TFrom, TTo&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers) &lt;span class="kwrd"&gt;where&lt;/span&gt; TTo : TFrom
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TFrom), &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TTo), name, &lt;span class="kwrd"&gt;null&lt;/span&gt;, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type t, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(t, &lt;span class="kwrd"&gt;null&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt;, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, LifetimeManager lifetimeManager, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(T), &lt;span class="kwrd"&gt;null&lt;/span&gt;, name, lifetimeManager, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType&amp;lt;TFrom, TTo&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, LifetimeManager lifetimeManager, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers) &lt;span class="kwrd"&gt;where&lt;/span&gt; TTo : TFrom
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TFrom), &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(TTo), name, lifetimeManager, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type t, LifetimeManager lifetimeManager, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(t, &lt;span class="kwrd"&gt;null&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt;, lifetimeManager, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type t, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(t, &lt;span class="kwrd"&gt;null&lt;/span&gt;, name, &lt;span class="kwrd"&gt;null&lt;/span&gt;, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type from, Type to, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers)
  {
    container.RegisterType(from, to, &lt;span class="kwrd"&gt;null&lt;/span&gt;, &lt;span class="kwrd"&gt;null&lt;/span&gt;, injectionMembers);
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container;
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type t, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, LifetimeManager lifetimeManager, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(t, &lt;span class="kwrd"&gt;null&lt;/span&gt;, name, lifetimeManager, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type from, Type to, LifetimeManager lifetimeManager, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(from, to, &lt;span class="kwrd"&gt;null&lt;/span&gt;, lifetimeManager, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IUnityContainer RegisterType(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type from, Type to, &lt;span class="kwrd"&gt;string&lt;/span&gt; name, &lt;span class="kwrd"&gt;params&lt;/span&gt; InjectionMember[] injectionMembers)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.RegisterType(from, to, name, &lt;span class="kwrd"&gt;null&lt;/span&gt;, injectionMembers);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; T Resolve&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; (T)container.Resolve(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(T));
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; T Resolve&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, &lt;span class="kwrd"&gt;string&lt;/span&gt; name)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; (T)container.Resolve(&lt;span class="kwrd"&gt;typeof&lt;/span&gt;(T), name);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; Resolve(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container, Type t)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; container.Resolve(t, &lt;span class="kwrd"&gt;null&lt;/span&gt;);
  }
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; ResolveAll&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;this&lt;/span&gt; IUnityContainer container)
  {
    &lt;span class="rem"&gt;//return new &amp;lt;ResolveAll&amp;gt;d__0&amp;lt;T&amp;gt;(-2) { &amp;lt;&amp;gt;4__this = this };&lt;/span&gt;
    &lt;span class="rem"&gt;//This implementation requires more effort than I am willing to give (6hours till my holiday!)&lt;/span&gt;
  }
}&lt;/pre&gt;

&lt;p&gt;Bloody hell. Imagine trying to implement that on every class that implemented the interface!&lt;/p&gt;

&lt;p&gt;While I know this entire post is academic as we cant change Unity, but I hope that sews some seeds for other developers so that when they design their next interface it wont have silly overloads that just make the consuming developer's job harder than it ought to be.&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-5941973729379465295?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/5941973729379465295/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=5941973729379465295' title='5 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5941973729379465295'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5941973729379465295'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2009/08/how-not-to-write-interface-in-c-30.html' title='How not to write an Interface in C# 3.0'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>5</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-7077209294887395392</id><published>2009-07-26T02:00:00.001+01:00</published><updated>2010-08-28T18:18:50.552+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Code Quality'/><title type='text'>Code inspections</title><content type='html'>&lt;p&gt;Code Inspections (or Code Reviews or Peer Reviews) is a technique a team can implement to improve the quality of the software they deliver. It is initially a bit of a cultural shift for many teams but can produce benefits not just in software but if done well also in team morale.&lt;/p&gt;  &lt;h3&gt;Goals&lt;/h3&gt;  &lt;p&gt;The goals for performing a Code Inspection are the following:&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;To cross pollinate Domain knowledge &lt;/li&gt;    &lt;li&gt;To cross pollinate technical knowledge &lt;/li&gt;    &lt;li&gt;To maintain a consistent team process &lt;/li&gt;    &lt;li&gt;To identify any obvious errors&lt;/li&gt; &lt;/ol&gt;  &lt;br /&gt;A code inspection should be an enjoyable experience where two developers are able to bond and cooperatively improve the quality of software delivered. The exercise should not feel like a witch-hunt or a boasting exercise for one developer to flex their ability over another. Initially the exercise may feel somewhat uncomfortable for the team, this is usually due to many different styles and tolerances the each member of the team brings to the collective skill set. In these scenarios it is better to agree amongst the team the level of detail that is in the remit of the inspections.  &lt;h3&gt;Introducing a team to Code Inspections&lt;/h3&gt; It is probably best if a team ease into code inspections, for it is better to be doing some code inspections and forgiving style differences than it is to be too aggressive in initial code inspections and cause tension in the team which sees the exercise become avoided. While this may be difficult to accept initially, one must remember that increasing the quality of today's code is of less importance than spreading the knowledge through out the team and maintain a quality team spirit. To know what to target in initial inspections, the team should conduct a brief team meeting and pick a handful of areas that the team agree needs work. This way we can get the biggest gain without creating to much friction.  &lt;h4&gt;Tools&lt;/h4&gt; The &amp;quot;what&amp;quot; to look for is of less importance than the process itself but the process can be aided quite nicely by the use of automated tools. In the .NET community the tools I would recommend are FxCop (or the Visual Studio Code Analysis), Simian (identifies duplicate code) and NCover (for test coverage).  &lt;br /&gt;To ease into code inspections I think it is best to set the bar quite low. For FxCop just enable the following Rules  &lt;ul&gt;   &lt;li&gt;Design &lt;/li&gt;    &lt;li&gt;Naming &lt;/li&gt;    &lt;li&gt;Performance &lt;/li&gt;    &lt;li&gt;Security &lt;/li&gt;    &lt;li&gt;Usage&lt;/li&gt; &lt;/ul&gt; While some teams may have their own style that might conflict with some of the styles in FxCop, ultimately this is a community standard now. As developers move between jobs it is great to eliminate this kind of induction friction when all .NET developers can be &amp;quot;singing from the same hymn sheet&amp;quot;.   &lt;br /&gt;Simian provides the ability to set a tolerance of duplication to 6 lines of duplicate code. This should be fine.  &lt;br /&gt;Assuming the team is TDD or at least writing tests the the bar for test coverage could start at something like 80%. While I understand that chasing 100% test coverage can be frowned upon, it is nice to know that code was writing for a reason and does what it was intended on doing.  &lt;h4&gt;Setting expectations&lt;/h4&gt; Once the initial team meeting has been completed a set of expectations should be drawn up. This will be the bench mark for code inspections. The benchmark should be set at a level that everyone in the team agrees that they are happy for their code to be &amp;quot;rejected&amp;quot; if it does not meet the expectations. As you can imagine this in itself will lower the bar quite considerably as developers know that there are circumstances beyond their control which may prohibit them meeting the expectations that they would like to meet. Project deadlines, new technologies and processes can affect a developers ability to meet these goals. Remember the goals for code inspection is not perfect code, it is to improve the ability of the team to create better code, and continually get better at creating better code.  &lt;br /&gt;An example for an initial code inspection check list may look like this for a C# 3.0 project:  &lt;ol&gt;   &lt;li&gt;Exceptions that are explicitly thrown from a public or protected members must be documented with XML comments. &lt;/li&gt;    &lt;li&gt;FxCop Naming and Performance rules must be met. &lt;/li&gt;    &lt;li&gt;Classes should be testable. &lt;/li&gt; &lt;/ol&gt; While this is a very small list of things to consider, just setting these expectations combined with knowledge sharing that the team would perform would see a dramatic improvement on any team not already doing code inspections.  &lt;br /&gt;Once the team is comfortable with the process and culture of code inspections, have another meeting to raise the bar a little bit. Again, refrain from being too eager. All team member should feel comfortable with the expectations being set.  &lt;h3&gt;Performing Code Inspections&lt;/h3&gt; Be fore we cover the actual actions of what to do when doing a code inspection just quickly remeber the goals of a code inspection  &lt;ol&gt;   &lt;li&gt;To cross pollinate Domain knowledge &lt;/li&gt;    &lt;li&gt;To cross pollinate technical knowledge &lt;/li&gt;    &lt;li&gt;To maintain a consistent team process &lt;/li&gt;    &lt;li&gt;To identify any obvious errors &lt;/li&gt; &lt;/ol&gt;  &lt;br /&gt;The inspection is not to create perfect code.  &lt;br /&gt;Steps to perform a code inspection (the first few step are as a courtesy to the reviewer):  &lt;ol&gt;   &lt;li&gt;First perform a quick review yourself. &lt;/li&gt;    &lt;li&gt;Indicate to the person you would like to review your code that you will want some of their time in a few moments. It is important that this person not be the same few people. Have a method where you cycle through the team (clock wise round the office, youngest to oldest etc). Generally you will want to do most of your reviews with your immediate team, but if you have a larger development team/department that can be involved in the inspection be sure to include them too. *&lt;/li&gt;    &lt;li&gt;Perform any automated analysis (FxCop, Simian, Unit tests etc...) &lt;/li&gt;    &lt;li&gt;Open all the necessary documents ready to go, and consider the logical path to show the reviewer through your code. &lt;/li&gt;    &lt;li&gt;Some prefer to review code on paper. This is very good for removing the desire to solve any problems with the code, it also allows you to easily make notes against the code and possibly perform the review in a quiet place. However, I also think that if done properly this creates a mass of wasted paper and ink. &lt;/li&gt;    &lt;li&gt;When both parties are ready, have the author describe the intent of the code to the reviewer. This should start with a 10 second overview of what set of code does.&amp;#160; &lt;/li&gt;    &lt;li&gt;Show the reviewer the output of any automated analysis (FxCop, Tests, Coverage etc.). Obviously the results of which should met the set expectations.&lt;/li&gt;    &lt;li&gt;If at the computer give the reviewer the mouse and keyboard. If using a print out have the print out in front of the reviewer. &lt;/li&gt;    &lt;li&gt;Describe what the code does, ideally from entry point to each of the leaves. Very good code will basically read like prose anyway so this would be very easy. &lt;/li&gt;    &lt;li&gt;The reviewer sets the pace of the review by scrolling or navigating to classes/methods as they understand the code. &lt;/li&gt;    &lt;li&gt;The reviewer prompts for &amp;quot;what-if&amp;quot; scenarios and bookmarks any concerns (Ctrl+k+k in Visual Studio). No attempt is made to &amp;quot;fix&amp;quot; any code by either party. &lt;/li&gt;    &lt;li&gt;As the reviewer bookmarks any code they should also take a note of why the bookmark was made (Unclear code, not meeting agreed expectations, possible error etc). This can be done on paper or if available a Code Inspection prompt sheet.&lt;/li&gt;    &lt;li&gt;The author generally will identify most of their mistakes as they describe the code to the reviewer. &lt;/li&gt;    &lt;li&gt;If the code has been flagged in any way that would fail to meet the set expectations -or- would result in probably faulty software; the Author requests the the Reviewer come back to verify their changes and approve the code.** &lt;/li&gt;    &lt;li&gt;Once the review(s) have come to a point where no probable faults exists in the code and the team expectations are met the code review is complete.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;   &lt;br /&gt;&lt;em&gt;*In my experience my project teams have been generally in sizes of 3-8. In these scenarios I would try to have each member of the team review my code over the course of a week. Once I had engaged each team member I would next engage someone from another team. This allows for a knowledge transfers across teams too (like finding out each team is using different logging tools!).     &lt;br /&gt;&lt;/em&gt;&lt;/p&gt;  &lt;p&gt;&lt;em&gt;**By having the Author suggest that they fix their code, this creates far less stress for the reviewer to feel as if they are judging the authors code. Essentially the reviewer is a soundboard and prompt for the author.&lt;/em&gt;&lt;/p&gt;  &lt;h3&gt;Hints and Tips&lt;/h3&gt;  &lt;ul&gt;   &lt;li&gt;Ensure that the team is clear that both the Reviewer and the Author are there to find any defects. It is a cooperative approach. &lt;/li&gt;    &lt;li&gt;Focus on &lt;b&gt;finding &lt;/b&gt;defects and failed expectations, &lt;b&gt;not&lt;/b&gt; fixing them.&lt;/li&gt;    &lt;li&gt;The biggest benefit for performing Code Inspections is that it creates a culture where the team all get better technically and also domain knowledge is not isolated to pockets of people. &lt;/li&gt;    &lt;li&gt;Inspect all new and modified code &lt;/li&gt;    &lt;li&gt;For best results review often and review early. Not many developers write so much code that 4 reviews in a day would be necessary, but not may developers would write so little code that only 1 or no code reviews would be done in a day. An exmple of a set of code to review could be when an MVP screen is complete; review the Model, View, Presenter and tests. I imagine few developer produce more than 4 tested screens per day.&lt;/li&gt;    &lt;li&gt;As you get better at code reviews they should become less and less formal and quicker to execute. Extreme Programming takes peer review to the next level by have 2 developer work together constantly in a fashion called Pair Programming.&lt;/li&gt;    &lt;li&gt;Some teams keep track of their code reviews an can create statistics to analyse where current weaknesses are. If you see value in this than give it a go, but make sure it doesn't just create &amp;quot;busy work&amp;quot;. I believe that if the inspections are done correctly the team will know that there is an area of need and should raise it appropriately. &lt;/li&gt;    &lt;li&gt;Code reviews should be done at the time the code was completed. New code should not be started until the current code has been inspected and approved. Keeping thing fresh in your head is key to a good review. It also means that &amp;quot;unfinished&amp;quot;/un-inspected code doesn't just slip out into production. &lt;/li&gt;    &lt;li&gt;Some source/version control systems allow you to attribute check ins. If this is the case then code that has passed a check in can be attributed ideally with the reviewer's details. This should then allow the team to analyse all code that has not been reviewed (ie. last check-in for a file was not attributed).&lt;/li&gt; &lt;/ul&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-7077209294887395392?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/7077209294887395392/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=7077209294887395392' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7077209294887395392'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7077209294887395392'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2009/07/code-inspections.html' title='Code inspections'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-5709130556299478228</id><published>2009-07-09T23:12:00.001+01:00</published><updated>2010-08-28T18:22:04.540+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Concurrency'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>.NET Parallel Framework - Videos</title><content type='html'>&lt;p&gt;Way back in June 2008 &lt;a href="http://www.albahari.com/" target="_blank"&gt;Joe Albahari&lt;/a&gt; gave a presentation on the upcoming parallel programming features in .NET 4.0. I have finally published the recording of his session here. Just for reference the Parallel Framework encompasses PLINQ and is sometimes referred to as the TPL (Task Parallel Library) or System.Threading.dll&lt;/p&gt;  &lt;p&gt;Sorry about the delay in the post.&lt;/p&gt;  &lt;p&gt;&lt;a href="http://cid-76a2ea424cb9f9ae.skydrive.live.com/browse.aspx/Videos/Joe%20Albahari%20PFX" target="_blank"&gt;Joe Albarhari Parallel FX and PLINQ videos : 6 videos @ ~10min and 40-50MB each.&lt;/a&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-5709130556299478228?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/5709130556299478228/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=5709130556299478228' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5709130556299478228'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5709130556299478228'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2009/07/net-parallel-framework-videos.html' title='.NET Parallel Framework - Videos'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-6882282017333297866</id><published>2009-06-06T00:26:00.001+01:00</published><updated>2010-08-28T18:22:45.449+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Concurrency'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Responsive WPF User Interfaces Part 7</title><content type='html'>&lt;h3&gt;Creating a responsive Image control&lt;/h3&gt;  &lt;p&gt;In &lt;a title="Responsive WPF User Interfaces Part 6 - Unresponsive Controls" href="http://leecampbell.blogspot.com/2009/05/responsive-wpf-user-interfaces-part-6.html" target="_blank"&gt;part 6&lt;/a&gt; we discovered problems even when we follow the guidelines from this series. In this case we find that sometimes it can be the controls themselves that are the cause of the lagging interface. In part 6 it was the Image control that was to blame. I make the assumption that it was trying to perform it's bitmap decoding on my precious dispatcher thread. However not only Image controls can get ugly, Charles Petzold shows some problems you may find when using chart controls (or any Items Control) in his &lt;a title="Writing More Efficient Items Controls - MSDN Article" href="http://msdn.microsoft.com/en-us/magazine/dd483292.aspx" target="_blank"&gt;Writing More Efficient Items Controls&lt;/a&gt; article.&lt;/p&gt;  &lt;p&gt;The first thing I wanted to do was to just sub class &lt;a title="Image Class" href="http://msdn.microsoft.com/en-us/library/system.windows.controls.image.aspx" target="_blank"&gt;Image&lt;/a&gt; however, I personally was stumped as to how I would then create my control template for it. Next I actually only wanted to accept URIs as my source so that I can do the decoding from file to an &lt;a title="ImageSource Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imagesource.aspx" target="_blank"&gt;ImageSource&lt;/a&gt; myself explicitly and not on the UI thread via a TypeConverter. So I want a sub class of Control with a dependency property of UriSource and then 3 read-only properties &lt;a title="ImageSource Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imagesource.aspx" target="_blank"&gt;ImageSource&lt;/a&gt;, IsLoading and HasLoadFailed. UriSource will provide the hook to bind your file name to. ImageSource will then provide the decoded &lt;a title="ImageSource Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imagesource.aspx" target="_blank"&gt;ImageSource&lt;/a&gt; to be displayed. IsLoading and HasLoadFailed will be there so that you can update the UI appropriate to the lifecycle of the image.&lt;/p&gt;  &lt;p&gt;The Style and control template I came up for this design was this:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Style&lt;/span&gt; &lt;span class="attr"&gt;TargetType&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{x:Type controls:Thumbnail}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt; &lt;span class="attr"&gt;Property&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Template&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter.Value&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ControlTemplate&lt;/span&gt; &lt;span class="attr"&gt;TargetType&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{x:Type controls:Thumbnail}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Image&lt;/span&gt; &lt;span class="attr"&gt;x:Name&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;ImageThumbnail&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;Source&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{TemplateBinding Image}&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;HorizontalAlignment&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{TemplateBinding HorizontalAlignment}&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;VerticalAlignment&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{TemplateBinding VerticalAlignment}&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;MaxHeight&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{TemplateBinding MaxHeight}&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;MaxWidth&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{TemplateBinding MaxWidth}&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;Stretch&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Uniform&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;StretchDirection&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;DownOnly&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;ControlTemplate&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Setter.Value&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Where I want to use the Thumbnail control I can have some XAML that hides and shows a loading indicator. This example here just shows the text &amp;quot;Loading Image...&amp;quot; but would probably have a nice animation or an indeterminate progress indicator.&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Border&lt;/span&gt; &lt;span class="attr"&gt;CornerRadius&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;4&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;BorderBrush&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Silver&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;BorderThickness&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;1&amp;quot;&lt;/span&gt;
        &lt;span class="attr"&gt;Width&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;150&amp;quot;&lt;/span&gt;
        &lt;span class="attr"&gt;Height&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;150&amp;quot;&lt;/span&gt;
        &lt;span class="attr"&gt;Margin&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;10&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Grid&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;local:Thumbnail&lt;/span&gt; &lt;span class="attr"&gt;x:Name&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Thumbnail&amp;quot;&lt;/span&gt;
                     &lt;span class="attr"&gt;MaxWidth&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;148&amp;quot;&lt;/span&gt;
                     &lt;span class="attr"&gt;MaxHeight&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;148&amp;quot;&lt;/span&gt;
                     &lt;span class="attr"&gt;UriSource&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding}&amp;quot;&lt;/span&gt; 
                     &lt;span class="attr"&gt;HorizontalAlignment&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Center&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;VerticalAlignment&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Center&amp;quot;&lt;/span&gt;
                     &lt;span class="attr"&gt;ToolTip&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;local:Thumbnail.Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Style&lt;/span&gt; &lt;span class="attr"&gt;TargetType&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{x:Type local:Thumbnail}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
          &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt; &lt;span class="attr"&gt;Property&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visibility&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visible&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
          &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Style.Triggers&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt; &lt;span class="attr"&gt;Binding&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding RelativeSource={RelativeSource Self}, Path=IsLoading}&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;True&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
              &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt; &lt;span class="attr"&gt;Property&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visibility&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Collapsed&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
          &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Style.Triggers&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;local:Thumbnail.Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;local:Thumbnail&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;

    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;TextBlock&lt;/span&gt; &lt;span class="attr"&gt;Text&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Loading image...&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;Foreground&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Gray&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;HorizontalAlignment&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Center&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;VerticalAlignment&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Center&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;TextBlock.Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
          &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Style&lt;/span&gt; &lt;span class="attr"&gt;TargetType&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;TextBlock&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
              &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt; &lt;span class="attr"&gt;Property&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visibility&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visible&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
              &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Style.Triggers&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt; &lt;span class="attr"&gt;Binding&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding ElementName=Thumbnail, Path=IsLoading}&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;False&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt; &lt;span class="attr"&gt;Property&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visibility&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Collapsed&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
                  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
              &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Style.Triggers&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;    
          &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;TextBlock.Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;TextBlock&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Grid&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Border&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Well that is the easy bit, the public API. Trust me it gets more interesting.&lt;/p&gt;

&lt;p&gt;My gut feeling was basically take the code from reflector and use that to decode Uris to ImageSource objects, but perform the action on a background thread. Two problems here: &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Most of the fun code that happens when the URI is being parsed and then decoded, is internal. :-( &lt;/li&gt;

  &lt;li&gt;You cant pass most sub-classes of &lt;a title="ImageSource Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imagesource.aspx" target="_blank"&gt;ImageSource&lt;/a&gt; across threads. If you create them on one thread they cant be accessed on another thread. So this stops us blindly copying code from reflector as all that code only runs on the dispatcher thread so wont face this problem. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We do have something to work with however: &lt;a title="WriteableBitmap Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx" target="_blank"&gt;WriteableBitmap&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;In some vain attempt at brevity (he says in his 7th post in the series!), I will try to skip over all of the brick walls I faced and jump straight to the solution I came up with. This was a great learning experience for me, and in the spirit of a learning experience &lt;a title="ArtemisWest.Demo.ResponsiveWPF.zip" href="http://cid-76a2ea424cb9f9ae.skydrive.live.com/self.aspx/Blog/ResponsiveUI/ArtemisWest.Demo.ResponsiveWPF.zip" target="_blank"&gt;the code&lt;/a&gt; is fairly rough (with TODO comments still intact). I will try to build this control into a stable control but in its current state is very much demo-ware.&lt;/p&gt;

&lt;p&gt;First thing I want to achieve was to have the decoding and if possible the reading from disk happen off the UI thread. Lets start with the easy bit; reading the file into memory. I'm going to keep that simple and just go with grabbing the file as a byte array like this&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;byte&lt;/span&gt;[] buffer = File.ReadAllBytes(UriSource);&lt;/pre&gt;

&lt;p&gt;Next I want to decode the byte array into some form of ImageSource. To do this I have used a combination of the &lt;a title="BitmapDecoder Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapdecoder.aspx" target="_blank"&gt;BitmapDecoder&lt;/a&gt; and the &lt;a title="WriteableBitmap Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx" target="_blank"&gt;WriteableBitmap&lt;/a&gt;. First I take the byte array and load it into a &lt;a title="MemoryStream Class" href="http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx" target="_blank"&gt;MemoryStream&lt;/a&gt;, and then pass the stream to the &lt;a title="BitmapDecoder Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapdecoder.aspx" target="_blank"&gt;BitmapDecoder&lt;/a&gt; factory method &lt;a title="BitmapDecoder.Create method" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapdecoder.create.aspx" target="_blank"&gt;Create&lt;/a&gt;. This will return me an instance of one of its implementations (BitmapDecoder is abstract/MustInherit). From here I make a bold assumption that we only care about the first &amp;quot;Frame&amp;quot; of the image. I believe that most formats don't support multiple frames but formats like GIF do which allows them to have animation features. Anyway, in my demo-ware code I just take the first frame. &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; (Stream mem = &lt;span class="kwrd"&gt;new&lt;/span&gt; MemoryStream(buffer))
{
  BitmapDecoder imgDecoder = &lt;span class="kwrd"&gt;null&lt;/span&gt;;
  imgDecoder = BitmapDecoder.Create(mem, BitmapCreateOptions.None, BitmapCacheOption.None);

  BitmapFrame frame = imgDecoder.Frames[0];
  &lt;span class="kwrd"&gt;double&lt;/span&gt; scale = GetTransormScale(maxWidth, maxHeight, frame.PixelWidth, frame.PixelHeight);

  BitmapSource thumbnail = ScaleBitmap(frame, scale);

  &lt;span class="rem"&gt;// this will disconnect the stream from the image completely ...&lt;/span&gt;
  var writable = &lt;span class="kwrd"&gt;new&lt;/span&gt; WriteableBitmap(thumbnail);
  writable.Freeze();
  &lt;span class="kwrd"&gt;return&lt;/span&gt; writable;
}&lt;/pre&gt;

&lt;p&gt;From here I figure out the ratio that I want to scale it to. There doesn't seem much point in returning an 8MB image if we only want to see it as 300x300 does it? Next we request the image as what is almost our final product. We have a helper method scale the frame and return it as a &lt;a title="BitmapSource Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx" target="_blank"&gt;BitmapSource&lt;/a&gt;. We can't assign this &lt;a title="BitmapSource Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx" target="_blank"&gt;BitmapSource&lt;/a&gt; back to our ImageSource dependency property as they don't play nice over thread boundaries. So, the last thing we need to do is take the &lt;a title="BitmapSource Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapsource.aspx" target="_blank"&gt;BitmapSource&lt;/a&gt; we just generated and create a &lt;a title="WriteableBitmap Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx" target="_blank"&gt;WriteableBitmap&lt;/a&gt; from it and then call its Freeze method. This puts the &lt;a title="WriteableBitmap Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx" target="_blank"&gt;WriteableBitmap&lt;/a&gt; in an immutable state which then makes it thread safe. Whew!&lt;/p&gt;

&lt;p&gt;Just for reference here is the GetTransformScale method&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;double&lt;/span&gt; GetTransormScale(&lt;span class="kwrd"&gt;double&lt;/span&gt; maxWidth, &lt;span class="kwrd"&gt;double&lt;/span&gt; maxHeight, &lt;span class="kwrd"&gt;double&lt;/span&gt; currentWidth, &lt;span class="kwrd"&gt;double&lt;/span&gt; currentHeight)
{
  &lt;span class="kwrd"&gt;double&lt;/span&gt; xRatio = maxWidth / currentWidth;
  &lt;span class="kwrd"&gt;double&lt;/span&gt; yRatio = maxHeight / currentHeight;
  &lt;span class="kwrd"&gt;double&lt;/span&gt; resizeRatio = (xRatio &amp;gt; yRatio) ? xRatio : yRatio;
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (resizeRatio &amp;gt; 1)
    resizeRatio = 1;
  &lt;span class="kwrd"&gt;return&lt;/span&gt; resizeRatio;
}&lt;/pre&gt;
&lt;style type="text/css"&gt;
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }&lt;/style&gt;

&lt;p&gt;and the ScaleBitmap method&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; BitmapSource ScaleBitmap(BitmapSource source, &lt;span class="kwrd"&gt;double&lt;/span&gt; scale)
{
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (scale &amp;gt; 0.9999 &amp;amp;&amp;amp; scale &amp;lt; 1.0001)
  {
    &lt;span class="kwrd"&gt;return&lt;/span&gt; source;
  }
  var thumbnail = &lt;span class="kwrd"&gt;new&lt;/span&gt; TransformedBitmap();
  thumbnail.BeginInit();
  thumbnail.Source = source;
  var transformGroup = &lt;span class="kwrd"&gt;new&lt;/span&gt; TransformGroup();
  transformGroup.Children.Add(&lt;span class="kwrd"&gt;new&lt;/span&gt; ScaleTransform(scale, scale));
  thumbnail.Transform = transformGroup;
  thumbnail.EndInit();
  &lt;span class="kwrd"&gt;return&lt;/span&gt; thumbnail;
}&lt;/pre&gt;

&lt;p&gt;So all things considered, once you get over the decoding stuff and then wrestle with the various subclasses of &lt;a title="ImageSource Class" href="http://msdn.microsoft.com/en-us/library/system.windows.media.imagesource.aspx" target="_blank"&gt;ImageSource&lt;/a&gt; that play their part, its not too bad. But like I said earlier; it gets more interesting. So far we have only looked at how to decode the image, we have yet to consider how to make the call to perform the decoding. My first instinct was to make the call on any change to the UriSource property. However I may not have the MaxHeight and MaxWidth information at that point in time. This caused me much stress over when should I call this decode functionality. If no value is ever going to be set for MaxHeight or MaxWidth then I should just process the image, but if first the UriSource is set then the MaxHeight, then the MaxWidth I would end up creating 3 asynchronous calls to render 3 different sized images. This would be a disaster as it would surely end up with race conditions and most likely the wrong sized image being displayed. The other obvious problem with that is that we would be performing 3 times the work. Hmm. &lt;/p&gt;

&lt;p&gt;My solution (and mileage may vary as I am green to concurrent programming models) was to create a stack of render requests for each instance of a Thumbnail. As a property was set then a request would be added to the stack and a request to start processing the stack would occur. Periodically while processing the image I would check to see if the current work was invalidated by any new requests to the stack. If the current request was invalid it would terminate its work. The request to start processing the stack would simply try to pop the last request from the stack and clear out all other requests (effectively ignoring stale requests). On returning from the render request it would loop back and try to pop anything new from the stack. This last part while important is very much implementation details and could vary dramatically from anything you may implement. I have just read over the code myself and I could do with some work. It is amazing what just 3months (and reading Joe Duffy's &lt;a title="Concurrent Programming for Windows" href="http://www.bluebytesoftware.com/books/winconc/winconc_book_resources.html" target="_blank"&gt;Concurrent Programming for Windows&lt;/a&gt;) does for your appreciation of your code.&lt;/p&gt;

&lt;p&gt;As always the code is available for you to have a play. Open it up, pick it to pieces, use what you like. Obviously I take no responsibility for the code if you do choose to use it as this is intended on being a learning exercise. Having said that I do try to produce good code for my demos so if you do see something that is not good enough let me know.&lt;/p&gt;

&lt;p&gt;This has been a fun series and I hope you liked it and learnt as much as I did from it.&lt;/p&gt;

&lt;p&gt;Back to series &lt;a href="http://leecampbell.blogspot.com/2009/01/responsive-uis-in-wpf-dispatchers-to.html"&gt;Table Of Contents&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Working version of the code can be found &lt;a href="http://cid-76a2ea424cb9f9ae.skydrive.live.com/self.aspx/Blog/ResponsiveUI/ArtemisWest.Demo.ResponsiveWPF.zip"&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-6882282017333297866?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/6882282017333297866/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=6882282017333297866' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/6882282017333297866'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/6882282017333297866'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2009/06/responsive-wpf-user-interfaces-part-7.html' title='Responsive WPF User Interfaces Part 7'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-6682177154415557644</id><published>2009-05-26T23:43:00.001+01:00</published><updated>2010-08-28T18:22:45.450+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Concurrency'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Responsive WPF User Interfaces Part 6</title><content type='html'>&lt;h3&gt;Unresponsive Controls&lt;/h3&gt;  &lt;p&gt;Sorry about the unreasonable delay between this post and the last post in this series. Interestingly readers that have been following the series have already jumped ahead to see that not all is fine even if you follow the guidance provided. 'Arne' &lt;a title="Comment regarding unresponsive progress bar when loading images" href="http://leecampbell.blogspot.com/2009/02/responsive-wpf-user-interfaces-part-5.html#c7565543627537946548"&gt;makes a comment&lt;/a&gt; on the last post that he is having some problems even when he follows the guidance especially when loading a lot of images. Some of the team I work with are currently working with graphing/charting products that are great with tens and hundreds of rows of data but create an unresponsive UI when pushed to use thousands of rows of data (eg +5 years of daily stock info).&lt;/p&gt;  &lt;p&gt;So if we are following the rules what can we do? Well let us look at a concrete problem first and for consistency let's stay with the PhotoAlbum project. For a quick refresher, we have a &amp;quot;ViewModel&amp;quot; with a property Images that is of type ObservableCollection&amp;lt;Uri&amp;gt;. The XAML snippet that displays the Images looks like this:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ListBox&lt;/span&gt; &lt;span class="attr"&gt;ItemsSource&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding Images}&amp;quot;&lt;/span&gt;
         &lt;span class="attr"&gt;ScrollViewer&lt;/span&gt;.&lt;span class="attr"&gt;HorizontalScrollBarVisibility&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Disabled&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ListBox.ItemTemplate&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;DataTemplate&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Border&lt;/span&gt; &lt;span class="attr"&gt;Background&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;AliceBlue&amp;quot;&lt;/span&gt;
              &lt;span class="attr"&gt;CornerRadius&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;2&amp;quot;&lt;/span&gt;
              &lt;span class="attr"&gt;Width&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;150&amp;quot;&lt;/span&gt;
              &lt;span class="attr"&gt;Height&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;150&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Image&lt;/span&gt; &lt;span class="attr"&gt;Source&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding}&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;MaxHeight&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;148&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;MaxWidth&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;148&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;Stretch&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Uniform&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;StretchDirection&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;DownOnly&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;HorizontalAlignment&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Center&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;VerticalAlignment&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Center&amp;quot;&lt;/span&gt;
               &lt;span class="attr"&gt;ToolTip&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding}&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Border&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;DataTemplate&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;ListBox.ItemTemplate&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ListBox.ItemsPanel&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ItemsPanelTemplate&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;WrapPanel&lt;/span&gt; &lt;span class="attr"&gt;IsItemsHost&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;True&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;ItemsPanelTemplate&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;ListBox.ItemsPanel&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;ListBox&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Now in theory there is nothing wrong with this XAML. From a declarative programming point of view, I think it is well written (Ed: Cause I wrote it!) as it describes what we want (Items in the ListBox to be wrapped horizontally, displayed as Images within a border.&lt;/p&gt;

&lt;p&gt;The problem with this declarative code is what most people fear with declarative code: what is actually happening under the hood? Before we trek too far, if I run the code (see example 6_UnresponsiveImages in the code example) I can select folders with small amount of small images just fine. The application runs ok. The current code becomes a problem when I point it to folders with large images. This is compounded when there are lots of those large images or when I am running on a slower/older computer. &lt;/p&gt;

&lt;p&gt;We will quickly go off track to consider the likelihood of the large image slow computer problem. Digital cameras currently are getting cheaper and the quality is going up. Mid range cameras range between 8-12 megapixel and can have in excess of 8GB of memory.&amp;#160; Phones now are coming out with 5-8 megapixel cameras. If you come back and read this 12months from now, I guess you will laugh at the small sizes I refer to. Next consider the average user's computer. Rightly or wrongly, the release of vista saw very few new features that users felt they needed. Many people still run Win XP and do so on old hardware. Pentium 4 chips are still pervasive in many homes and offices. Loading a gig of 10 megapixel images in our current app does prove to be a performance problem.&lt;/p&gt;

&lt;p&gt;We actually have 2 problems here:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;loading of the image in it's full resolution &lt;/li&gt;

  &lt;li&gt;loading the image on the UI thread &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We will only discuss issue 2 because technically this series is about responsive UIs, not performance (similar but not the same problem). So to get to the bottom of why our UI is laggy even though we have &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;loaded our Images on a different thread, &lt;/li&gt;

  &lt;li&gt;updated the UI using the dispatcher &lt;/li&gt;

  &lt;li&gt;and written nice XAML &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;we should understand a little bit about the Image control. The Image control has a Source property. Most often this source property is given a string or Uri, however some may have noticed that it actually is of type ImageSource. Through the magic of TypeConverters our strings and URI are converted to an appropriate sub class of ImageSource, most likely BitmapFrame. From having a quick browse over the code implemented around the ImageSource, BitmapSource, BitmapFrame &amp;amp; BitmapDecoder, I can only deduct that the only code executed off the UI thread is the downloading of the image where the source is a URI with http or https protocol. One may then argue that &amp;quot;well if it came from the file system wouldn't that be so fast that it could be done on the UI thread&amp;quot;. One may argue that, but that is not the whole argument. Once the file has been read from disk it still must be decoded and then resized. While this generally is fast and would normally take less than 1 second, we should remember back to some magic number I made up that was 250ms-330ms (1/4 to 1/3 of a second) is the max the UI thread can hang for before it is very clear to the user. Now if I load just 8 images that each take 330ms-500ms to load from disk, decode and then resize this will create an awful user experience for the ender user as the progress bar stutters and images appear and the mouse is jerky. &lt;/p&gt;

&lt;p&gt;To reproduce the problems discussed in this post you will want to get some hi-res images and load up the example code that can be found &lt;a title="ArtemisWest.Demo.ResponsiveWPF.zip" href="http://cid-76a2ea424cb9f9ae.skydrive.live.com/self.aspx/Blog/ResponsiveUI/ArtemisWest.Demo.ResponsiveWPF.zip"&gt;here&lt;/a&gt;. Try out the 6th example and point the source folder of the pop up widow to your folder with the hi-res images.&lt;/p&gt;

&lt;p&gt;&lt;a title="Responsive WPF User Interfaces - Responsive Controls" href="http://leecampbell.blogspot.com/2009/06/responsive-wpf-user-interfaces-part-7.html" target="_blank"&gt;Next post&lt;/a&gt; we will look at the issues we will face with solving the problem of Images that kill the responsiveness of our UI. We will discuss fun things like decoders, freezables and maybe the parallel extensions that will become part of .NET 4.0&lt;/p&gt;

&lt;p&gt;Previous - &lt;a title="Responsive WPF User Interfaces Part 5 - Testing multi-threaded WPF code" href="http://leecampbell.blogspot.com/2009/02/responsive-wpf-user-interfaces-part-5.html"&gt;Responsive WPF User Interfaces Part 5&lt;/a&gt; - Testing multi-threaded WPF code&lt;/p&gt;

&lt;p&gt;Next - &lt;a title="Responsive WPF User Interfaces Part 7 - Responsive Controls" href="http://leecampbell.blogspot.com/2009/06/responsive-wpf-user-interfaces-part-7.html" target="_blank"&gt;Responsive WPF User Interfaces Part 7&lt;/a&gt; - Responsive Controls&lt;/p&gt;

&lt;p&gt;Back to series &lt;a href="http://leecampbell.blogspot.com/2009/01/responsive-uis-in-wpf-dispatchers-to.html"&gt;Table Of Contents&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Working version of the code can be found &lt;a href="http://cid-76a2ea424cb9f9ae.skydrive.live.com/self.aspx/Blog/ResponsiveUI/ArtemisWest.Demo.ResponsiveWPF.zip"&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-6682177154415557644?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/6682177154415557644/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=6682177154415557644' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/6682177154415557644'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/6682177154415557644'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2009/05/responsive-wpf-user-interfaces-part-6.html' title='Responsive WPF User Interfaces Part 6'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-7362862293619656449</id><published>2009-05-21T09:32:00.001+01:00</published><updated>2009-05-21T09:33:38.308+01:00</updated><title type='text'>VS 2010 Beta</title><content type='html'>Yahoo! Shiny new toys to play with 
&lt;a href="http://blogs.msdn.com/wpfsdk/archive/2009/05/20/visual-studio-10-beta-1-bits-are-now-publically-available.aspx"&gt;http://blogs.msdn.com/wpfsdk/archive/2009/05/20/visual-studio-10-beta-1-bits-are-now-publically-available.aspx&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-7362862293619656449?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/7362862293619656449/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=7362862293619656449' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7362862293619656449'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/7362862293619656449'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2009/05/vs-2010-beta.html' title='VS 2010 Beta'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-5661357197546652724</id><published>2009-02-16T22:46:00.002Z</published><updated>2012-01-24T16:53:38.554Z</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Concurrency'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Responsive WPF User Interfaces Part 5</title><content type='html'>&lt;h3&gt;Testing multi-threaded WPF code&lt;/h3&gt;  

&lt;strong&gt;Stop press: Dont use this method. Read the article, but follow comment at bottom of post (ie Use Rx instead)&lt;/strong&gt;

&lt;p&gt;In the last post in this series we took a rather long way to get to the multi-threaded result we were looking for. This was because we decided to separate out our code in cohesive parts that allowed for more maintainable code. The popular method of creating maintainable code currently is through Unit Testing. An even better approach would be to apply Test Driven Development. TDD is a style of design where tests outlining our goals are written first and then code to satisfy those tests is created. Having identified the technical challenges of keeping a WPF application responsive, namely; the concepts related to the Dispatcher and parallel programming, we can now step back again to see the bigger picture as we did in part 4, to move forward.&lt;/p&gt;  &lt;p&gt;In this post we will drive out our presentation model through tests and discover the issues related to testing WPF code and in particular testing the multi-threaded code. Just to set expectations, there is an assumption here that the reader is familiar with WPF Data Templates and unit testing with a mocking framework. &lt;/p&gt;  &lt;p&gt;From my experience with unit testing it is always good to start off with a set of requirements that we could turn into tests. Continuing with our example of a thumbnail viewer, lets create a list of our requirements:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;User can choose a folder &lt;/li&gt;    &lt;li&gt;Can see what folder was selected &lt;/li&gt;    &lt;li&gt;Will list all images in that directory and sub directories &lt;/li&gt;    &lt;li&gt;Will indicate when it is processing &lt;/li&gt;    &lt;li&gt;Cannot set folder while processing &lt;/li&gt;    &lt;li&gt;The user interface will remain responsive during processing &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;For brevity, I will try to cheat as much as I can so more time can be spent on the technical issues of testing multi-threaded WPF code and less time spouting TDD goodness. I will first cheat by making the assumption that this is WPF code so will need implement constructs such as ICommand and INotifyPropertyChanged.&lt;/p&gt;  &lt;p&gt;From these requirements I eventually came to the following test cases:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;[TestClass]
&lt;span class="kwrd"&gt;class&lt;/span&gt; PhotoAlbumModelFixture
{
    [TestMethod]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetSourceCommand_sets_SourcePath(){}
    
    [TestMethod]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetSourceCommand_calls_FileService_with_value_from_FolderSelector(){}

    [TestMethod] 
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetSourceCommand_calls_FileService_with_an_ImageOnly_filter() {}

    [TestMethod]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetSourceCommand_populates_images_from_FileService(){}

    [TestMethod]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetSourceCommand_recursively_calls_FileService(){}

    [TestMethod]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetSourceCommand_does_not_call_FileService_with_empty_value(){}

    [TestMethod]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetSourceCommand_sets_IsLoading_to_True(){}

    [TestMethod]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetSourceCommand_is_disabled_when_IsLoading(){}

    [TestMethod]
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; FileService_is_called_Async(){}
}&lt;/pre&gt;

&lt;p&gt;When writing some of the tests I found that standard unit test code was fine. When I started to implement my code that had to make multithreaded calls, however, testing became problematic.&lt;/p&gt;

&lt;p&gt;For example, my first attempt to write the &amp;quot;SetSourceCommand_calls_FileService_with_value_from_FolderSelector&amp;quot; test looked like this:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[TestMethod]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; SetSourceCommand_calls_FileService_with_value_from_FolderSelector()
{
    Rhino.Mocks.MockRepository mockery = &lt;span class="kwrd"&gt;new&lt;/span&gt; Rhino.Mocks.MockRepository();
    ArtemisWest.Demo.ResponsiveUI._4_MultiThreaded.IFileService fileService = mockery.DynamicMock&amp;lt;ArtemisWest.Demo.ResponsiveUI._4_MultiThreaded.IFileService&amp;gt;();
    ArtemisWest.Demo.ResponsiveUI._5_MultiThreadedTest.IFolderSelector folderSelector = mockery.DynamicMock&amp;lt;ArtemisWest.Demo.ResponsiveUI._5_MultiThreadedTest.IFolderSelector&amp;gt;();

    PhotoAlbumModel model = &lt;span class="kwrd"&gt;new&lt;/span&gt; PhotoAlbumModel(Dispatcher.CurrentDispatcher, fileService, folderSelector);

    &lt;span class="kwrd"&gt;using&lt;/span&gt; (mockery.Record())
    {
        Expect.Call(folderSelector.SelectFolder()).Return(FolderPath);
        Expect.Call(fileService.ListFiles(FolderPath, &lt;span class="kwrd"&gt;null&lt;/span&gt;)).Return(EmptyList).IgnoreArguments().Constraints(
          Rhino.Mocks.Constraints.Is.Equal(FolderPath),
          Rhino.Mocks.Constraints.Is.Anything());
        Expect.Call(fileService.ListDirectories(FolderPath)).Return(EmptyList);
    }

    &lt;span class="kwrd"&gt;using&lt;/span&gt; (mockery.Playback())
    {
        model.SetSourcePathCommand.Execute(&lt;span class="kwrd"&gt;null&lt;/span&gt;);
    }
}&lt;/pre&gt;

&lt;p&gt;And following TDD rules of just write enough code to satisfy the test, my implementation of the Execute command handler looks like this:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;void&lt;/span&gt; ExecuteSetSourcePath(&lt;span class="kwrd"&gt;object&lt;/span&gt; sender, ExecutedEventArgs e)
{
    SourcePath = &lt;span class="kwrd"&gt;this&lt;/span&gt;.folderSelector.SelectFolder();
    IsLoading = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
    LoadPath(SourcePath);
    IsLoading = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
}

&lt;span class="kwrd"&gt;void&lt;/span&gt; LoadPath(&lt;span class="kwrd"&gt;string&lt;/span&gt; path)
{
    IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; files = fileService.ListFiles(path, IsImage);
    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; item &lt;span class="kwrd"&gt;in&lt;/span&gt; files)
    {
        Images.Add(item);
    }

    IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; directories = fileService.ListDirectories(path);
    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; item &lt;span class="kwrd"&gt;in&lt;/span&gt; directories)
    {
        LoadPath(item);
    }
}&lt;/pre&gt;

&lt;p&gt;Astute readers will notice the complete lack of &amp;quot;Responsive UI Code&amp;quot;. Well I have yet to reach my test that specifies that the call to FileService should be asynchronous. So after I have finished writing all of my other tests and the code to support them, I write some test code to enforce the responsive requirement:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[TestMethod]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; FileService_is_called_Async()
{
    SlowFileServiceFake fileService = &lt;span class="kwrd"&gt;new&lt;/span&gt; SlowFileServiceFake();
    Rhino.Mocks.MockRepository mockery = &lt;span class="kwrd"&gt;new&lt;/span&gt; Rhino.Mocks.MockRepository();
    ArtemisWest.Demo.ResponsiveUI._5_MultiThreadedTest.IFolderSelector folderSelector = mockery.DynamicMock&amp;lt;ArtemisWest.Demo.ResponsiveUI._5_MultiThreadedTest.IFolderSelector&amp;gt;();

    PhotoAlbumModel model = &lt;span class="kwrd"&gt;new&lt;/span&gt; PhotoAlbumModel(Dispatcher.CurrentDispatcher, fileService, folderSelector);

    &lt;span class="kwrd"&gt;using&lt;/span&gt; (mockery.Record())
    {
        Expect.Call(folderSelector.SelectFolder()).Return(FolderPath);
    }

    &lt;span class="kwrd"&gt;using&lt;/span&gt; (mockery.Playback())
    {
        model.SetSourcePathCommand.Execute(&lt;span class="kwrd"&gt;null&lt;/span&gt;);
        &lt;span class="rem"&gt;//Due to the sleeps in the stub this should only have 1 item at this stage.&lt;/span&gt;
        Assert.IsTrue(model.Images.Count &amp;lt; fileService.ExpectedFiles.Count);
    }
    Thread.Sleep(300);
    CollectionAssert.AreEquivalent(fileService.ExpectedFiles, model.Images);
}

&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; SlowFileServiceFake : ArtemisWest.Demo.ResponsiveUI._4_MultiThreaded.IFileService
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; ExpectedFiles = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;() { &lt;span class="str"&gt;&amp;quot;value0&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value1&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value2&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value3&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value4&amp;quot;&lt;/span&gt;, &lt;span class="str"&gt;&amp;quot;value5&amp;quot;&lt;/span&gt; };

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; ListFiles(&lt;span class="kwrd"&gt;string&lt;/span&gt; path, Predicate&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; filter)
    {
        &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var item &lt;span class="kwrd"&gt;in&lt;/span&gt; ExpectedFiles)
        {
            &lt;span class="kwrd"&gt;yield&lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; item;
            Thread.Sleep(30);
        }
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; ListDirectories(&lt;span class="kwrd"&gt;string&lt;/span&gt; path)
    {
        &lt;span class="kwrd"&gt;return&lt;/span&gt; EmptyList;
    }
}&lt;/pre&gt;

&lt;p&gt;Here I have used a Fake to provide canned results with a hard coded delay. In theory this should drip feed values to the presentation model. &lt;/p&gt;

&lt;p&gt;I now go back to update my model to get the tests to pass. Following my own advice I change the code to look like the following:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;void&lt;/span&gt; ExecuteSetSourcePath(&lt;span class="kwrd"&gt;object&lt;/span&gt; sender, ExecutedEventArgs e)
{
    &lt;span class="kwrd"&gt;string&lt;/span&gt; folder = &lt;span class="kwrd"&gt;this&lt;/span&gt;.folderSelector.SelectFolder();
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (!&lt;span class="kwrd"&gt;string&lt;/span&gt;.IsNullOrEmpty(folder))
    {
        SourcePath = folder;
        StartLoadingFiles(SourcePath);
    }
}

&lt;span class="kwrd"&gt;void&lt;/span&gt; StartLoadingFiles(&lt;span class="kwrd"&gt;string&lt;/span&gt; path)
{
    BackgroundWorker fileWorker = &lt;span class="kwrd"&gt;new&lt;/span&gt; BackgroundWorker();
    fileWorker.DoWork += (sender, e) =&amp;gt;
    {
        LoadPath(path);
    };
    fileWorker.RunWorkerCompleted += (sender, e) =&amp;gt;
    {
        IsLoading = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
    };
    fileWorker.RunWorkerAsync();
}

&lt;span class="kwrd"&gt;void&lt;/span&gt; LoadPath(&lt;span class="kwrd"&gt;string&lt;/span&gt; path)
{
    IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; files = fileService.ListFiles(path, IsImage);
    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; item &lt;span class="kwrd"&gt;in&lt;/span&gt; files)
    {
        dispatcher.Invoke(&lt;span class="kwrd"&gt;new&lt;/span&gt; Action(() =&amp;gt; { Images.Add(item); }));
    }

    IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; directories = fileService.ListDirectories(path);
    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; item &lt;span class="kwrd"&gt;in&lt;/span&gt; directories)
    {
        LoadPath(item);
    }
}&lt;/pre&gt;

&lt;p&gt;To my surprise this code does not satisfy the test! The reason is because the Dispatcher is not in an Executing loop. This would normally be started by WPF when the application starts, but here we are just in test code. The solution lies with the &lt;a title="System.Windows.Threading.DispatcherFrame" href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherframe.aspx"&gt;DispatcherFrame&lt;/a&gt;. A dispatcher frame represents an execution loop in a Dispatcher. We can kick start this loop by simply instantiating a new &lt;a title="System.Windows.Threading.DispatcherFrame" href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherframe.aspx" target="_blank"&gt;DispatcherFrame&lt;/a&gt; and calling &lt;a title="System.Windows.Threading.Dispatcher.PushFrame method" href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.pushframe.aspx" target="_blank"&gt;Dispatcher.PushFrame&lt;/a&gt; with it as the parameter. See &lt;a title="Dan Crevier&amp;#39;s Blog : DM-V-VM part 4: Unit testing the DataModel" href="http://blogs.msdn.com/dancre/archive/2006/07/26/679870.aspx" target="_blank"&gt;Dan Crevier's&lt;/a&gt; blog for a really simple way to unit test in this fashion. If we implement Dan's method we end up with the following test code:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[TestMethod]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; FileService_is_called_Async()
{
    SlowFileServiceFake fileService = &lt;span class="kwrd"&gt;new&lt;/span&gt; SlowFileServiceFake();
    Rhino.Mocks.MockRepository mockery = &lt;span class="kwrd"&gt;new&lt;/span&gt; Rhino.Mocks.MockRepository();
    ArtemisWest.Demo.ResponsiveUI._5_MultiThreadedTest.IFolderSelector folderSelector = mockery.DynamicMock&amp;lt;ArtemisWest.Demo.ResponsiveUI._5_MultiThreadedTest.IFolderSelector&amp;gt;();

    PhotoAlbumModel model = &lt;span class="kwrd"&gt;new&lt;/span&gt; PhotoAlbumModel(Dispatcher.CurrentDispatcher, fileService, folderSelector);

    &lt;span class="kwrd"&gt;using&lt;/span&gt; (mockery.Record())
    {
        Expect.Call(folderSelector.SelectFolder()).Return(FolderPath);
    }

    DispatcherFrame frame = &lt;span class="kwrd"&gt;new&lt;/span&gt; DispatcherFrame();
    model.PropertyChanged += (sender, e) =&amp;gt; 
    {
        &lt;span class="kwrd"&gt;if&lt;/span&gt; (e.PropertyName == &lt;span class="str"&gt;&amp;quot;IsLoading&amp;quot;&lt;/span&gt; &amp;amp;&amp;amp; !model.IsLoading)
        {
            frame.Continue = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
        }
    };

    &lt;span class="kwrd"&gt;using&lt;/span&gt; (mockery.Playback())
    {
        model.SetSourcePathCommand.Execute(&lt;span class="kwrd"&gt;null&lt;/span&gt;);
        &lt;span class="rem"&gt;//Due to the sleeps in the stub this should only have 1 item at this stage.&lt;/span&gt;
        Assert.IsTrue(model.Images.Count &amp;lt; fileService.ExpectedFiles.Count);
        Dispatcher.PushFrame(frame);
    }
    Thread.Sleep(300);
    CollectionAssert.AreEquivalent(fileService.ExpectedFiles, model.Images);
}&lt;/pre&gt;

&lt;p&gt;We could call it a day here, however I am not happy enough with this style of coding. My first problem is the explicit sleep I have in there. This makes my test slow. The fastest this test will ever run is 300ms. I could replace that with some sort of loop to check progress but then my test code is looking less like test code and more like low level code to dance-around dispatchers. This raises my other issue; the clutter I have added by adding the DispatcherFrame stuff.&lt;/p&gt;

&lt;p&gt;My solution here was to create a construct that allowed me to code my intentions in a way that I thought to be clearer. I wanted to be able to &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;test code that would involve multi-threaded code and the dispatcher &lt;/li&gt;

  &lt;li&gt;specify what condition defined its completion &lt;/li&gt;

  &lt;li&gt;specify a timeout &lt;/li&gt;

  &lt;li&gt;treat the code block as a blocking call &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The result I came up with is the following:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[TestMethod]
&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; FileService_is_called_Async()
{
    Rhino.Mocks.MockRepository mockery = &lt;span class="kwrd"&gt;new&lt;/span&gt; Rhino.Mocks.MockRepository();
    SlowFileServiceFake fileService = &lt;span class="kwrd"&gt;new&lt;/span&gt; SlowFileServiceFake();
    ArtemisWest.Demo.ResponsiveUI._5_MultiThreadedTest.IFolderSelector folderSelector = mockery.DynamicMock&amp;lt;ArtemisWest.Demo.ResponsiveUI._5_MultiThreadedTest.IFolderSelector&amp;gt;();

    PhotoAlbumModel model = &lt;span class="kwrd"&gt;new&lt;/span&gt; PhotoAlbumModel(Dispatcher.CurrentDispatcher, fileService, folderSelector);
    &lt;span class="kwrd"&gt;using&lt;/span&gt; (mockery.Record())
    {
        Expect.Call(folderSelector.SelectFolder()).Return(FolderPath);
    }

    &lt;span class="kwrd"&gt;using&lt;/span&gt; (DispatcherTester dispatcherTester = &lt;span class="kwrd"&gt;new&lt;/span&gt; DispatcherTester(Dispatcher.CurrentDispatcher))
    {
        model.PropertyChanged += (sender, e) =&amp;gt;
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (e.PropertyName == &lt;span class="str"&gt;&amp;quot;IsLoading&amp;quot;&lt;/span&gt; &amp;amp;&amp;amp; !model.IsLoading)
                dispatcherTester.Complete();
        };
        dispatcherTester.Execute(() =&amp;gt;
          {
              model.SetSourcePathCommand.Execute(&lt;span class="kwrd"&gt;null&lt;/span&gt;);
              Assert.IsTrue(model.Images.Count &amp;lt; fileService.ExpectedFiles.Count);
          },
          &lt;span class="kwrd"&gt;new&lt;/span&gt; TimeSpan(0, 0, 2));
    }
    CollectionAssert.AreEquivalent(fileService.ExpectedFiles, model.Images);
}&lt;/pre&gt;

&lt;p&gt;This code describes a block of code that may require the use of the dispatcher, the condition where the asynchronous code is considered complete and a TimeSpan for a timeout. The test code is still not perfect but I think it is a step in the right direction.&lt;/p&gt;

&lt;p&gt;The code for the DispatcherTester looks something like this:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;internal&lt;/span&gt; &lt;span class="kwrd"&gt;sealed&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; DispatcherTester : IDisposable
{
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; Dispatcher dispatcher;
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; DispatcherFrame dispatcherFrame = &lt;span class="kwrd"&gt;new&lt;/span&gt; DispatcherFrame();

  &lt;span class="kwrd"&gt;public&lt;/span&gt; DispatcherTester(Dispatcher dispatcher)
  {
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.dispatcher = dispatcher;
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; Dispatcher Dispatcher
  {
    get { &lt;span class="kwrd"&gt;return&lt;/span&gt; dispatcher; }
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Execute(Action action, TimeSpan timeout)
  {
    Execute(action, timeout, &lt;span class="kwrd"&gt;new&lt;/span&gt; TimeSpan(10));
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Execute(Action action, TimeSpan timeout, TimeSpan wait)
  {
    Stopwatch stopwatch = Stopwatch.StartNew();
    action.Invoke();
    Dispatcher.PushFrame(dispatcherFrame);

    &lt;span class="kwrd"&gt;while&lt;/span&gt; (dispatcherFrame.Continue &amp;amp;&amp;amp; stopwatch.Elapsed &amp;lt; timeout)
    {
      Thread.Sleep(wait);
    }
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (stopwatch.Elapsed &amp;gt;= timeout)
    {
      dispatcherFrame.Continue = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
      Dispatcher.DisableProcessing();
      Dispatcher.ExitAllFrames();
      &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; TimeoutException();
    }
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Complete()
  {
    dispatcherFrame.Continue = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
  }

  &lt;span class="preproc"&gt;#region&lt;/span&gt; IDisposable Members

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Dispose()
  {
    dispatcherFrame.Continue = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
  }

  &lt;span class="preproc"&gt;#endregion&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;If any other developers have hit problems trying to write unit tests for their WPF code then I hope that this snippet of code helps. For those that are interested, the end result for the Model looks like &lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; PhotoAlbumModel : INotifyPropertyChanged
{
  &lt;span class="preproc"&gt;#region&lt;/span&gt; Fields
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; Dispatcher dispatcher;
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; _4_MultiThreaded.IFileService fileService;
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; IFolderSelector folderSelector;
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; DelegateCommand setSourcePathCommand;
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; ObservableCollection&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; images = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObservableCollection&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; sourcePath;
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; isLoading = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
  &lt;span class="preproc"&gt;#endregion&lt;/span&gt;

  &lt;span class="kwrd"&gt;public&lt;/span&gt; PhotoAlbumModel(Dispatcher dispatcher, _4_MultiThreaded.IFileService fileService, IFolderSelector folderSelector)
  {
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.dispatcher = dispatcher;
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.fileService = fileService;
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.folderSelector = folderSelector;
    setSourcePathCommand = &lt;span class="kwrd"&gt;new&lt;/span&gt; DelegateCommand(ExecuteSetSourcePath, CanSetSourcePath);
    &lt;span class="kwrd"&gt;this&lt;/span&gt;.PropertyChanged += (sender, e) =&amp;gt; { &lt;span class="kwrd"&gt;if&lt;/span&gt; (e.PropertyName == &lt;span class="str"&gt;&amp;quot;IsLoading&amp;quot;&lt;/span&gt;) setSourcePathCommand.OnCanExecuteChanged(); };
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; ObservableCollection&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Images
  {
    get { &lt;span class="kwrd"&gt;return&lt;/span&gt; images; }
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsLoading
  {
    get { &lt;span class="kwrd"&gt;return&lt;/span&gt; isLoading; }
    &lt;span class="kwrd"&gt;private&lt;/span&gt; set
    {
      isLoading = &lt;span class="kwrd"&gt;value&lt;/span&gt;;
      OnPropertyChanged(&lt;span class="str"&gt;&amp;quot;IsLoading&amp;quot;&lt;/span&gt;);
    }
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; SourcePath
  {
    get { &lt;span class="kwrd"&gt;return&lt;/span&gt; sourcePath; }
    &lt;span class="kwrd"&gt;private&lt;/span&gt; set
    {
      sourcePath = &lt;span class="kwrd"&gt;value&lt;/span&gt;;
      OnPropertyChanged(&lt;span class="str"&gt;&amp;quot;SourcePath&amp;quot;&lt;/span&gt;);
    }
  }

  &lt;span class="kwrd"&gt;public&lt;/span&gt; ICommand SetSourcePathCommand { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; setSourcePathCommand; } }

  &lt;span class="preproc"&gt;#region&lt;/span&gt; Command handlers
  &lt;span class="kwrd"&gt;void&lt;/span&gt; CanSetSourcePath(&lt;span class="kwrd"&gt;object&lt;/span&gt; sender, CanExecuteEventArgs e)
  {
    e.CanExecute = !IsLoading;
  }

  &lt;span class="kwrd"&gt;void&lt;/span&gt; ExecuteSetSourcePath(&lt;span class="kwrd"&gt;object&lt;/span&gt; sender, ExecutedEventArgs e)
  {
    &lt;span class="kwrd"&gt;string&lt;/span&gt; folder = &lt;span class="kwrd"&gt;this&lt;/span&gt;.folderSelector.SelectFolder();
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (!&lt;span class="kwrd"&gt;string&lt;/span&gt;.IsNullOrEmpty(folder))
    {
      SourcePath = folder;
      StartLoadingFiles(SourcePath);
    }
  }
  &lt;span class="preproc"&gt;#endregion&lt;/span&gt;

  &lt;span class="preproc"&gt;#region&lt;/span&gt; Private method
  &lt;span class="kwrd"&gt;void&lt;/span&gt; StartLoadingFiles(&lt;span class="kwrd"&gt;string&lt;/span&gt; path)
  {
    IsLoading = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
    BackgroundWorker fileWorker = &lt;span class="kwrd"&gt;new&lt;/span&gt; BackgroundWorker();
    fileWorker.DoWork += (sender, e) =&amp;gt;
    {
      LoadPath(path);
    };
    fileWorker.RunWorkerCompleted += (sender, e) =&amp;gt;
    {
      IsLoading = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
    };
    fileWorker.RunWorkerAsync();
  }

  &lt;span class="kwrd"&gt;void&lt;/span&gt; LoadPath(&lt;span class="kwrd"&gt;string&lt;/span&gt; path)
  {
    IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; files = fileService.ListFiles(path, IsImage);
    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; item &lt;span class="kwrd"&gt;in&lt;/span&gt; files)
    {
      dispatcher.Invoke(&lt;span class="kwrd"&gt;new&lt;/span&gt; Action(() =&amp;gt; { Images.Add(item); }));
    }

    IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; directories = fileService.ListDirectories(path);
    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; item &lt;span class="kwrd"&gt;in&lt;/span&gt; directories)
    {
      LoadPath(item);
    }
  }

  &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsImage(&lt;span class="kwrd"&gt;string&lt;/span&gt; file)
  {
    &lt;span class="kwrd"&gt;string&lt;/span&gt; extension = file.ToLower().Substring(file.Length - 4);
    &lt;span class="kwrd"&gt;switch&lt;/span&gt; (extension)
    {
      &lt;span class="kwrd"&gt;case&lt;/span&gt; &lt;span class="str"&gt;&amp;quot;.bmp&amp;quot;&lt;/span&gt;:
      &lt;span class="kwrd"&gt;case&lt;/span&gt; &lt;span class="str"&gt;&amp;quot;.gif&amp;quot;&lt;/span&gt;:
      &lt;span class="kwrd"&gt;case&lt;/span&gt; &lt;span class="str"&gt;&amp;quot;.jpg&amp;quot;&lt;/span&gt;:
      &lt;span class="kwrd"&gt;case&lt;/span&gt; &lt;span class="str"&gt;&amp;quot;.png&amp;quot;&lt;/span&gt;:
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;true&lt;/span&gt;;
      &lt;span class="kwrd"&gt;default&lt;/span&gt;:
        &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;false&lt;/span&gt;;
    }
  }
  &lt;span class="preproc"&gt;#endregion&lt;/span&gt;

  &lt;span class="preproc"&gt;#region&lt;/span&gt; INotifyPropertyChanged Members
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;event&lt;/span&gt; PropertyChangedEventHandler PropertyChanged;
&lt;font color="#008000"&gt;&lt;/font&gt;
  &lt;span class="kwrd"&gt;protected&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; OnPropertyChanged(&lt;span class="kwrd"&gt;string&lt;/span&gt; propertyName)
  {
    PropertyChangedEventHandler handler = PropertyChanged;
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (handler != &lt;span class="kwrd"&gt;null&lt;/span&gt;)
    {
      handler(&lt;span class="kwrd"&gt;this&lt;/span&gt;, &lt;span class="kwrd"&gt;new&lt;/span&gt; PropertyChangedEventArgs(propertyName));
    }
  }
  &lt;span class="preproc"&gt;#endregion&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;Notice that the Folder dialogue code from the previous post has now been pushed out to an interface which cleans up the code and also allows us to test this model.&lt;/p&gt;

&lt;p&gt;The data template looks almost identical to the previous post's window xaml:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;DataTemplate&lt;/span&gt; &lt;span class="attr"&gt;DataType&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{x:Type local:PhotoAlbumModel}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;DataTemplate.Resources&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;BooleanToVisibilityConverter&lt;/span&gt; &lt;span class="attr"&gt;x:Key&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;boolToVisConverter&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;DataTemplate.Resources&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;DockPanel&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;DockPanel&lt;/span&gt; &lt;span class="attr"&gt;DockPanel&lt;/span&gt;.&lt;span class="attr"&gt;Dock&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Top&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ProgressBar&lt;/span&gt; &lt;span class="attr"&gt;IsIndeterminate&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;True&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Height&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;18&amp;quot;&lt;/span&gt; 
                   &lt;span class="attr"&gt;DockPanel&lt;/span&gt;.&lt;span class="attr"&gt;Dock&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Top&amp;quot;&lt;/span&gt; 
                   &lt;span class="attr"&gt;Visibility&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding Path=IsLoading, 
                                Converter={StaticResource boolToVisConverter}}&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Button&lt;/span&gt; &lt;span class="attr"&gt;x:Name&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;SetSourcePath&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Command&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding Path=SetSourcePathCommand}&amp;quot;&lt;/span&gt; 
              &lt;span class="attr"&gt;DockPanel&lt;/span&gt;.&lt;span class="attr"&gt;Dock&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Right&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;Set Source&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Button&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Border&lt;/span&gt; &lt;span class="attr"&gt;BorderThickness&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;1&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;BorderBrush&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;LightBlue&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Margin&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;3&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Grid&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
          &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;TextBlock&lt;/span&gt; &lt;span class="attr"&gt;Text&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding SourcePath}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;TextBlock.Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
              &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Style&lt;/span&gt; &lt;span class="attr"&gt;TargetType&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;TextBlock&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt; &lt;span class="attr"&gt;Property&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visibility&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visible&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
                &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Style.Triggers&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt; &lt;span class="attr"&gt;Binding&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding SourcePath}&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt; &lt;span class="attr"&gt;Property&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visibility&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Collapsed&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
                    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt; &lt;span class="attr"&gt;Binding&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding SourcePath}&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{x:Null}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt; &lt;span class="attr"&gt;Property&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visibility&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Collapsed&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
                  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Style.Triggers&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
              &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;TextBlock.Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
          &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;TextBlock&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
          &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;TextBlock&lt;/span&gt; &lt;span class="attr"&gt;Text&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Source not set&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Foreground&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;LightGray&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;FontStyle&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Italic&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;TextBlock.Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
              &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Style&lt;/span&gt; &lt;span class="attr"&gt;TargetType&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;TextBlock&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt; &lt;span class="attr"&gt;Property&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visibility&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Collapsed&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
                &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Style.Triggers&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt; &lt;span class="attr"&gt;Binding&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding SourcePath}&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt; &lt;span class="attr"&gt;Property&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visibility&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visible&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
                    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                  &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt; &lt;span class="attr"&gt;Binding&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding SourcePath}&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{x:Null}&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;Setter&lt;/span&gt; &lt;span class="attr"&gt;Property&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visibility&amp;quot;&lt;/span&gt; &lt;span class="attr"&gt;Value&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visible&amp;quot;&lt;/span&gt;&lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
                  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;DataTrigger&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
                &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Style.Triggers&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
              &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
            &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;TextBlock.Style&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
          &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;TextBlock&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
        &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Grid&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
      &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;Border&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;DockPanel&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
    &lt;span class="kwrd"&gt;&amp;lt;&lt;/span&gt;&lt;span class="html"&gt;ListView&lt;/span&gt; &lt;span class="attr"&gt;ItemsSource&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;{Binding Images}&amp;quot;&lt;/span&gt; 
              &lt;span class="attr"&gt;ScrollViewer&lt;/span&gt;.&lt;span class="attr"&gt;VerticalScrollBarVisibility&lt;/span&gt;&lt;span class="kwrd"&gt;=&amp;quot;Visible&amp;quot;&lt;/span&gt; &lt;span class="kwrd"&gt;/&amp;gt;&lt;/span&gt;
  &lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;DockPanel&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="kwrd"&gt;&amp;lt;/&lt;/span&gt;&lt;span class="html"&gt;DataTemplate&lt;/span&gt;&lt;span class="kwrd"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;I hope that the examples here &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;give some insight on how you too can unit test your code, &lt;/li&gt;

  &lt;li&gt;show why a model is a better option for your WPF applications as you can test them &lt;/li&gt;

  &lt;li&gt;give you the courage to write multi threaded code in your WPF models in the knowledge that you can test it &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;i&gt;Next&lt;/i&gt; we discover that sometimes controls can cause an unresponsive UI in Part 6.&lt;/p&gt;

&lt;p&gt;Previous - &lt;a title="Responsive WPF User Interfaces Part 4" href="http://leecampbell.blogspot.com/2009/02/responsive-wpf-user-interfaces-part-4.html" target="_blank"&gt;Responsive WPF User Interfaces Part 4&lt;/a&gt; - Multi-threaded Programming in WPF.&lt;/p&gt;

&lt;p&gt;Back to series &lt;a href="http://leecampbell.blogspot.com/2009/01/responsive-uis-in-wpf-dispatchers-to.html"&gt;Table Of Contents&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Working version of the code can be found &lt;a href="http://cid-76a2ea424cb9f9ae.skydrive.live.com/self.aspx/Blog/ResponsiveUI/ArtemisWest.Demo.ResponsiveWPF.zip"&gt;here&lt;/a&gt;&lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/455072646448673416-5661357197546652724?l=leecampbell.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://leecampbell.blogspot.com/feeds/5661357197546652724/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=455072646448673416&amp;postID=5661357197546652724' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5661357197546652724'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/455072646448673416/posts/default/5661357197546652724'/><link rel='alternate' type='text/html' href='http://leecampbell.blogspot.com/2009/02/responsive-wpf-user-interfaces-part-5.html' title='Responsive WPF User Interfaces Part 5'/><author><name>Lee Campbell</name><uri>http://www.blogger.com/profile/16932445715757919177</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='http://3.bp.blogspot.com/-C8m3LaC-a94/TX_4ZP4VgGI/AAAAAAAACpY/vUllSoNugPg/s220/Profile.jpg'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-455072646448673416.post-824298713739882493</id><published>2009-02-02T15:13:00.001Z</published><updated>2010-08-28T18:22:45.451+01:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='WPF'/><category scheme='http://www.blogger.com/atom/ns#' term='Concurrency'/><category scheme='http://www.blogger.com/atom/ns#' term='training'/><title type='text'>Responsive WPF User Interfaces Part 4</title><content type='html'>&lt;h3&gt;Multi-threaded Programming in WPF&lt;/h3&gt; In the last post (&lt;a title="Responsive WPF User Interface Part 3" href="http://leecampbell.blogspot.com/2009/02/responsive-wpf-user-interfaces-part-3.html"&gt;Part 3&lt;/a&gt;) of the series we found a way to get our UI responsive and provide some visual clue to the user that work was being performed. However we found that there were limitations to the model proposed as only small/fast pieces of work could be performed. Once a task started taking a longer time to process, the User Interface (UI) became unresponsive again. This was because the task were still being performed on the UI thread via the dispatcher. This post looks at how we can leverage the multi-threaded functionality in the .NET framework to perform tasks that have a long or unknown duration while keeping the UI responsive.   &lt;br /&gt;The .NET framework offers several ways to invoke work on a separate thread including:   &lt;ul&gt;   &lt;li&gt;The Start method on a System.Threading.Thread object &lt;/li&gt;    &lt;li&gt;BeginInvoke Method on a delegate &lt;/li&gt;    &lt;li&gt;QueueUserWork method on the System.Threading.ThreadPool type &lt;/li&gt;    &lt;li&gt;The RunWorkerAsync method on a System.ComponentModel.BackgroundWorker &lt;/li&gt; &lt;/ul&gt; The merits of each of these is beyond the scope of this post. I am going to pick one and run with it. Ideally I will discuss the merits in another post.   &lt;h3&gt;A quick code refactor*&lt;/h3&gt; I think it is fair to point out at the moment the adding concurrency handling to our code behind on the Window is going to balloon out the code. This concerns me as I think we already have a problem with single responsibility. The window code is clearly at the presentation layer. It has some properties relevant to the Presentation layer and then has some very specific code regarding the File System. I would like to move that code out in to a model. Doing so will realise several benefits:   &lt;ul&gt;   &lt;li&gt;The code will have a single responsibility (to serve as a presentation model) &lt;/li&gt;    &lt;li&gt;I should be come testable &lt;/li&gt;    &lt;li&gt;Ideally the implementation details could become pluggable (swap file system for SkyDrive, flickr, Database etc for example). However this is a benefit, not a goal of the changes we are about to make. &lt;/li&gt; &lt;/ul&gt; So in this next piece of code I will take the key parts that I want to keep in the model   &lt;ul&gt;   &lt;li&gt;the Images property (ObservableCollection&amp;lt;String&amp;gt;) &lt;/li&gt;    &lt;li&gt;the IsLoading property (bool) &lt;/li&gt;    &lt;li&gt;the SourcePath property (string) &lt;/li&gt;    &lt;li&gt;an implementation of INotifyPropertyChanged interface &lt;/li&gt;    &lt;li&gt;a new SetSourcePathCommand property. I prefer Commands to event handlers. Using a command will allow us to stop the user changing the Source while we are processing. &lt;/li&gt; &lt;/ul&gt; At a glance the new code will look like this:   &lt;br /&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; PhotoAlbumModel : INotifyPropertyChanged
{
  &lt;span class="preproc"&gt;#region&lt;/span&gt; Fields ...

  &lt;span class="kwrd"&gt;public&lt;/span&gt; ObservableCollection&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; Images {...}
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; IsLoading {...}
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; SourcePath {...}

  &lt;span class="kwrd"&gt;public&lt;/span&gt; ICommand SetSourcePathCommand { get { &lt;span class="kwrd"&gt;return&lt;/span&gt; setSourcePathCommand; } }

  &lt;span class="preproc"&gt;#region&lt;/span&gt; INotifyPropertyChanged Members...
}&lt;/pre&gt;

&lt;br /&gt;For this example I will use a custom implementation of ICommand that allows me to specify the delegates for the CanExecute and Execute methods. This implementation is called a DelegateCommand. There is an implementation of this in the &lt;a href="http://www.codeplex.com/CompositeWPF"&gt;Composite Application Guidance&lt;/a&gt; that I would recommend you use in your code. So I update my Model to use a delegate command and add two methods to handle the CanExecute and Execute behaviour. 

&lt;br /&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; DelegateCommand setSourcePathCommand;&lt;/pre&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; PhotoAlbumModel()
{
  setSourcePathCommand = &lt;span class="kwrd"&gt;new&lt;/span&gt; DelegateCommand(ExecuteSetSourcePath, CanSetSourcePath);
  &lt;span class="kwrd"&gt;this&lt;/span&gt;.PropertyChanged += (sender, e) =&amp;gt; { &lt;span class="kwrd"&gt;if&lt;/span&gt; (e.PropertyName == &lt;span class="str"&gt;&amp;quot;IsLoading&amp;quot;&lt;/span&gt;) setSourcePathCommand.OnCanExecuteChanged(); };
}&lt;/pre&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="preproc"&gt;#region&lt;/span&gt; Command handlers
&lt;span class="kwrd"&gt;void&lt;/span&gt; CanSetSourcePath(&lt;span class="kwrd"&gt;object&lt;/span&gt; sender, CanExecuteEventArgs e)
{
  e.CanExecute = !IsLoading;
}

&lt;span class="kwrd"&gt;void&lt;/span&gt; ExecuteSetSourcePath(&lt;span class="kwrd"&gt;object&lt;/span&gt; sender, ExecutedEventArgs e)
{
  System.Windows.Forms.FolderBrowserDialog openFolderDlg = &lt;span class="kwrd"&gt;new&lt;/span&gt; System.Windows.Forms.FolderBrowserDialog();
  openFolderDlg.RootFolder = Environment.SpecialFolder.Desktop;
  &lt;span class="kwrd"&gt;if&lt;/span&gt; (openFolderDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  {
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (!&lt;span class="kwrd"&gt;string&lt;/span&gt;.IsNullOrEmpty(openFolderDlg.SelectedPath))
    {
      SourcePath = openFolderDlg.SelectedPath;
      StartLoadingFiles(SourcePath);
    }
  }
}
&lt;span class="preproc"&gt;#endregion&lt;/span&gt;&lt;/pre&gt;

&lt;br /&gt;Bear with me during this reshaping of our code. I will get back to Responsive UIs, but I believe this is important. In our implementation of the Execute handler we call a method we have yet to create StartLoadingFiles. This is where our threading code will be isolated to. I think this makes our code much easier to understand, as so far the class is comprised of simple concepts like Properties, Notification Events &amp;amp; Commands. In our new StartLoadingFiles method we introduce our first Multi-threaded code by implementing a BackgroundWorker. 

&lt;br /&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="preproc"&gt;#region&lt;/span&gt; Private method
&lt;span class="kwrd"&gt;void&lt;/span&gt; StartLoadingFiles(&lt;span class="kwrd"&gt;string&lt;/span&gt; path)
{
  IsLoading = &lt;span class="kwrd"&gt;true&lt;/span&gt;;
  BackgroundWorker fileWorker = &lt;span class="kwrd"&gt;new&lt;/span&gt; BackgroundWorker();
  fileWorker.DoWork += (sender, e) =&amp;gt;
  {
    LoadPath(path);
  };
  fileWorker.RunWorkerCompleted += (sender, e) =&amp;gt;
  {
    IsLoading = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
  };
  fileWorker.RunWorkerAsync();
}

&lt;span class="kwrd"&gt;void&lt;/span&gt; LoadPath(&lt;span class="kwrd"&gt;string&lt;/span&gt; path)
{
  IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; files = fileService.ListFiles(path, IsImage);
  &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; item &lt;span class="kwrd"&gt;in&lt;/span&gt; files)
  {
    dispatcher.Invoke(&lt;span class="kwrd"&gt;new&lt;/span&gt; Action(() =&amp;gt; { Images.Add(item); }));
  }

  IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; directories = fileService.ListDirectories(path);
  &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; item &lt;span class="kwrd"&gt;in&lt;/span&gt; directories)
  {
    LoadPath(item);
  }
}

&lt;span class="kwrd"&gt;bool&lt;/span&gt; IsImage(&lt;span class="kwrd"&gt;string&lt;/span&gt; file){...} &lt;span class="rem"&gt;//Same implementation as before.&lt;/span&gt;
&lt;span class="preproc"&gt;#endregion&lt;/span&gt;&lt;/pre&gt;

&lt;br /&gt;I hope you agree that so far the code is fairly simple to read and understand &lt;em&gt;Ed-yes it still could be better, no it was not driven out by tests&lt;/em&gt;. We have introduced 3 methods here. One is our old friend IsImage that we stole from previous code. StartLoadingFiles method is our entry point to running the Multi-threaded code, and the LoadPath method is the code that will be executed from the BackgroundThread. Four things I would like to point out at this point: 

&lt;ol&gt;
  &lt;li&gt;The implementation of the BackgroundWorker is just one example of how you could kick off parallel execution. Don't take this method as best practice. &lt;/li&gt;

  &lt;li&gt;Note the use of dispatcher.Invoke in the for loop of the LoadPath method. We cant use BeginInvoke in a loop as the variable [item] is passed by ref. If we did, we would be setting the value of a reference type, passing the reference type to a the non-blocking call and then changing the value of the reference type by moving to the next value in the enumeration. This would result in most of the values queued on the dispatcher to just the value of the last item in the enumeration. &lt;/li&gt;

  &lt;li&gt;We have access to a private variable called dispatcher. Where did that come from? Will cover that in a moment. &lt;/li&gt;

  &lt;li&gt;We are calling ListFiles and ListDirectories methods on a variable called fileService. Operations on the file system have been delegated to another class now. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To actually make the new code work we have to introduce some new fields and create a constructor that enables these fields to be set. 
  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="preproc"&gt;#region&lt;/span&gt; Fields
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; Dispatcher dispatcher;
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; IFileService fileService;
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; DelegateCommand setSourcePathCommand;
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; ObservableCollection&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; images = &lt;span class="kwrd"&gt;new&lt;/span&gt; ObservableCollection&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;();
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; sourcePath;
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; isLoading = &lt;span class="kwrd"&gt;false&lt;/span&gt;;
&lt;span class="preproc"&gt;#endregion&lt;/span&gt;

&lt;span class="kwrd"&gt;public&lt;/span&gt; PhotoAlbumModel(Dispatcher dispatcher, IFileService fileService)
{
  &lt;span class="kwrd"&gt;this&lt;/span&gt;.dispatcher = dispatcher;
  &lt;span class="kwrd"&gt;this&lt;/span&gt;.fileService = fileService;
  setSourcePathCommand = &lt;span class="kwrd"&gt;new&lt;/span&gt; DelegateCommand(ExecuteSetSourcePath, CanSetSourcePath);
  &lt;span class="kwrd"&gt;this&lt;/span&gt;.PropertyChanged += (sender, e) =&amp;gt; { &lt;span class="kwrd"&gt;if&lt;/span&gt; (e.PropertyName == &lt;span class="str"&gt;&amp;quot;IsLoading&amp;quot;&lt;/span&gt;) setSourcePathCommand.OnCanExecuteChanged(); };
}&lt;/pre&gt;

&lt;p&gt;
  &lt;br /&gt;This also indicates that we have a new Interface of IFileService and lets give you an implementation of that interface FileSystemService. 

  &lt;br /&gt;&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IFileService
{
  IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; ListFiles(&lt;span class="kwrd"&gt;string&lt;/span&gt; path, Predicate&amp;lt;String&amp;gt; filter);
  IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; ListDirectories(&lt;span class="kwrd"&gt;string&lt;/span&gt; path);
}&lt;/pre&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; FileSystemService : IFileService
{
  &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; ListFiles(&lt;span class="kwrd"&gt;string&lt;/span&gt; path, Predicate&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; filter)
  {
    Collection&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; images = &lt;span class="kwrd"&gt;new&lt;/span&gt; Collection&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;
