<?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-5325631863209472986</id><updated>2011-11-27T22:37:09.136-02:00</updated><category term='c#'/><category term='dependency injection'/><category term='linq'/><category term='design patterns'/><category term='parallel extensions'/><category term='introduction'/><category term='iterator'/><category term='lambda expressions'/><category term='functional programming'/><category term='source code'/><category term='MQ'/><category term='code samples'/><category term='c# 3.5'/><category term='middleware'/><category term='events'/><category term='F#'/><category term='immutability'/><category term='concurrency'/><category term='c# 3.0'/><category term='extension methods'/><title type='text'>JP Labs</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>19</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-6875157284237407436</id><published>2010-12-29T18:35:00.000-02:00</published><updated>2010-12-29T18:35:31.502-02:00</updated><title type='text'>News time</title><content type='html'>News time, children!&lt;br /&gt;&lt;br /&gt;My blogging activity might be low recently, but there are two news worth mentioning.&lt;br /&gt;&lt;br /&gt;Fisrt, the repository move. I've been trying &lt;a href="http://mercurial.selenic.com/"&gt;Mercurial&lt;/a&gt; for some time. It's time to admit I like it. I you are interested in following the code I write, from now on you'll have to look at my Mercurial repository at &lt;a href="https://bitbucket.org/jpbochi/jplabscode"&gt;Bitbucket&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;I know that Google Code has Mercurial support, but I simply preferred to go to another site. One advantage of using a &lt;a href="http://en.wikipedia.org/wiki/Distributed_revision_control"&gt;distributed version control system&lt;/a&gt; is that I can move hosts any time I want, without loosing anything. Anyways, my experience with Bitbucket has been very good so far.&lt;br /&gt;&lt;br /&gt;Second and last, my blog url has changed. You might already have noticed, but you're now at &lt;a href="http://jplabs.bochi.it/"&gt;http://jplabs.bochi.it/&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Thanks for listening! And now, some music.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-6875157284237407436?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/6875157284237407436/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=6875157284237407436&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/6875157284237407436'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/6875157284237407436'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2010/12/news-time.html' title='News time'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-2649062183330100904</id><published>2010-10-15T10:24:00.001-03:00</published><updated>2010-10-15T10:28:46.913-03:00</updated><title type='text'>A Tale of Singletons and Global State</title><content type='html'>Some weeks ago, I received one odd feedback. I was talking to this guy and he said "A fellow of mine read in your blog that you are in favor of singletons. Is that true?" I remembered that &lt;a href="http://jp-labs.blogspot.com/2010/05/on-design-patterns-and-dependency.html"&gt;the post&lt;/a&gt; was ultimately about Design Patterns. I used some extrapolations of the Singleton Pattern to get to Dependency Injection. I never supported singletons. I just used it as a very simple and known pattern to get to something bigger. I was so astonished by the question that I couldn't answer it. At the time, I was not able to support my real opinion. Today, I'll try to express myself clearer.&lt;br /&gt;&lt;br /&gt;According to wikipedia, &lt;i&gt;the &lt;a href="http://en.wikipedia.org/wiki/Singleton_pattern"&gt;singleton pattern&lt;/a&gt; is a design pattern used to restrict the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.&lt;/i&gt; In the usual way it's implemented, there's a private constructor and an static property or method that always returns the same instance. There are a few big problem with such a class. One, it violates the single responsibility principle. A class should not be responsible for its own lifetime. Two, the singleton instance is attached to the global state.&lt;br /&gt;&lt;br /&gt;It happens that both these problems can be eliminated and we still have a singleton. The creation of the singleton could be delegated to a factory. And the factory doesn't have to be attached to the global state. That's what differentiates a good singleton (one instance per factory) from a bad singleton (one instance per AppDomain or JVM).&lt;br /&gt;&lt;br /&gt;I have seen a good deal of bad singletons in projects I've worked on. They caused me pain. Many times, I was forced to convert some of them into something nicer. I know how hard they are to test, and how they tend to create hidden dependencies. I don't like the bad singleton. Some people even say they are evil. Nevertheless, they are ubiquitous. Just for the sake of the example, let's consider the .NET framework. Here is a list of singletons (and static functions that access some form of global state) built in the framework:&lt;br /&gt;System.AppDomain.CurrentDomain;&lt;br /&gt;System.DateTime.Now;&lt;br /&gt;System.Environment.*;&lt;br /&gt;System.Globalization.CultureInfo.CurrentCulture;&lt;br /&gt;System.IO.File.Open(...);&lt;br /&gt;System.Random.Random(); //uses System.Environment.TickCount&lt;br /&gt;System.Threading.SynchronizationContext.Current;&lt;br /&gt;System.Threading.Thread.CurrentThread;&lt;br /&gt;System.Threading.Tasks.Task.Factory;&lt;br /&gt;System.Transactions.Transaction.Current;&lt;br /&gt;System.Web.HttpContext.Current;&lt;br /&gt;System.Windows.Application.Current;&lt;br /&gt;System.Windows.DependencyProperty.Register(...);&lt;br /&gt;System.Windows.EventManager.*;&lt;br /&gt;System.Windows.Forms.Application.*;&lt;br /&gt;System.Windows.Forms.MessageBox.Show(...);&lt;br /&gt;&lt;br /&gt;Of course, .NET is not an exception. All the main platforms we use today have quite a few examples like those. Do you know any singleton-free programming platform? The only one I've heard of is &lt;a href="http://en.wikipedia.org/wiki/Newspeak_%28programming_language%29"&gt;Newspeak&lt;/a&gt;. Why aren't there more languages like that? Why do we use programming platforms so packed with vicious singletons and APIs that access global state? I don't have a complete answer to these questions, but one thing is certain. There must be a good reason for them to be there. The cost of removing all singletons probably doesn't pay off. In fact, I think it's close to being impossible.&lt;br /&gt;&lt;br /&gt;Let's consider the computer's clock. In .NET, we can read the current time by reading the DateTime.Now property. Although it's not a classic singleton, it's completely equivalent to one. It could be like that: Clock.Instance.GetCurrentDateTime(). The real problem here is that we are accessing global state. Every time we read the value, it changes. Now, is that such a bad thing? Of course not. A clock is supposed to move without being told so. A stopped clock is useless. Would you blame the framework designers for coding a singleton in such a special case? I wouldn't. There's usually only one physical clock available in a machine anyway.&lt;br /&gt;&lt;br /&gt;What about a logical clock? I needed one once. The application I came to work with had a rule engine. Many of the rules were dependent on the current date and time. For example, the customer would be eligible for a fee waiver only if his/her last payment were due for less than a couple of days. No surprise, the team found out that rules like that were the hardest to test. The only way to fake the system time is by changing the computer's clock. However, it affected the application in other unforeseen ways, and that was not a viable solution. Not being able to test all the rules, the original team did the best they could with the time that was given to them. They deployed the application without testing everything.&lt;br /&gt;&lt;br /&gt;Nonetheless, the situation can always get worse. Another problem appeared. We realized that many users were working in a different time zone and that the application was using the machine's local time. It was supposed to use US Central Standard Time. Compensating the local time zone wouldn't fix it because some users had an incorrect time zone set. And the users could always fiddle with the local clock. In the end, we simply couldn't trust the system's time.&lt;br /&gt;&lt;br /&gt;The solution? I created a logical clock that gets synced with a trusted server every now and then, completely independent of the local time. I just provide the rule engine with a proper clock and the time zone bug was fixed. Since there's only one synced clock per rule engine (and one rule engine per application), the clock is a singleton. A good one though. Good enough to have one additional benefit. We could now test the time-dependent rules easily. All we need to do is to mock the clock.&lt;br /&gt;&lt;br /&gt;So, what's my take on singletons? They are a necessary evil that has to be understood and handled with care. If you really need to create one, make sure it's a good one.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-2649062183330100904?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/2649062183330100904/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=2649062183330100904&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/2649062183330100904'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/2649062183330100904'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2010/10/tale-of-singletons-and-global-state.html' title='A Tale of Singletons and Global State'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-7213812787663568777</id><published>2010-09-09T18:50:00.000-03:00</published><updated>2010-09-09T18:50:32.266-03:00</updated><title type='text'>Tweaked Events at CodeProject</title><content type='html'>Two days ago, I published my first article at CodeProject: &lt;a href="http://www.codeproject.com/KB/cs/TweakedEvents.aspx"&gt;Tweaked Events&lt;/a&gt; (ex-"Custom Events"). Go check it out! :)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-7213812787663568777?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/7213812787663568777/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=7213812787663568777&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/7213812787663568777'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/7213812787663568777'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2010/09/tweaked-events-at-codeproject.html' title='Tweaked Events at CodeProject'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-594650338230686848</id><published>2010-05-19T12:39:00.003-03:00</published><updated>2010-05-19T17:58:05.838-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='dependency injection'/><category scheme='http://www.blogger.com/atom/ns#' term='design patterns'/><title type='text'>On Design Patterns and Dependency Injection</title><content type='html'>&lt;p&gt;Since I heard of design patterns for the first time, there was one aspect of it that puzzled me. They seemed to be universally considered a good thing by itself. There seems to be a common belief that the lack of patterns in a program is a bad sign. Or, conversely, the ubiquitous presence of patterns in a software code is a good sign.&lt;/p&gt;&lt;p&gt;I never agreed to anything like that. Ideas like that go against my instincts. More specifically, the instinct to avoid recurrent code patterns (in the dictionary meaning). They are bad for maintenance, to mention one thing. Well, the so called design patterns are exactly that, recurrent code patterns. So, why are they are so popular? The reason is that their basic idea is mostly misinterpreted.&lt;/p&gt;&lt;p&gt;A while back, I read a very enlightening text written by &lt;a href="http://en.wikipedia.org/wiki/Mark_Dominus"&gt;Mark Dominus&lt;/a&gt; entitled &lt;a href="http://blog.plover.com/prog/design-patterns.html" target="_blank"&gt;Design patterns of 1972&lt;/a&gt;. He starts by saying:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;&amp;quot;Patterns&amp;quot; that are used recurringly in one language may be invisible or trivial in a different language.&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;And concludes affirming:&lt;/p&gt;&lt;blockquote&gt;&lt;p&gt;Patterns are signs of weakness in programming languages.&lt;/p&gt;&lt;/blockquote&gt;&lt;p&gt;I agree with him. And so did most of the people that read and commented about the article. &lt;a href="http://en.wikipedia.org/wiki/Ralph_Johnson" target="_blank"&gt;Ralph Johnson&lt;/a&gt; (one of the authors of the &lt;a href="http://en.wikipedia.org/wiki/Design_Patterns_%28book%29" target="_blank"&gt;”Design Patterns” book&lt;/a&gt;) wrote a &lt;a href="http://www.cincomsmalltalk.com/userblogs/ralph/blogView?entry=3335803396" target="_blank"&gt;reply&lt;/a&gt;. And Mark wrote a &lt;a href="http://blog.plover.com/prog/johnson.html" target="_blank"&gt;reply to Ralph’s reply&lt;/a&gt;. I think there are some ego sparks here and there, but they generally agree with each other. If you are surprised by their agreement, you definitely should read their texts.&lt;/p&gt;&lt;h4&gt;Creational Patterns and Dependency Injection&lt;/h4&gt;&lt;p&gt;Despite their value, I will not simply quote other people’s opinions. I have a point to make, too. I’ve been reviewing the whole subject recently, and an idea came to my mind. It’s not very innovative, but it’s worth phrasing anyway.&lt;/p&gt;&lt;p&gt;All &lt;a href="http://www.dofactory.com/Patterns/Patterns.aspx" target="_blank"&gt;creational patterns&lt;/a&gt; (namely Abstract Factory, Builder, Factory Method, Prototype, and Singleton) are no more than specific applications of &lt;a href="http://en.wikipedia.org/wiki/Dependency_injection" target="_blank"&gt;dependency injection&lt;/a&gt;.&lt;/p&gt;&lt;p&gt;I’ll try to build my case around the &lt;a href="http://en.wikipedia.org/wiki/Singleton_pattern" target="_blank"&gt;singleton pattern&lt;/a&gt;. It’s possibly the simplest pattern, and the easiest one to understand. To begin with, I do not want to advocate it as bad pattern. For many simple situations, it fits the problem perfectly. I see it as an extreme simplified solution to a possibly more complex problem. It has &lt;a href="http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx" target="_blank"&gt;drawbacks&lt;/a&gt;, though. Some cases require something similar, but just a little bit more sophisticated. I’ll go over some possible modifications to the singleton pattern through the rest of this article.&lt;/p&gt;&lt;p&gt;Before moving on, a comment. I’ll use some C# for my examples below for a single reason, it’s the language I know the most. I’m sure the general idea is valid for any language.&lt;/p&gt;&lt;h5&gt;- Global State and Object Life Cycle&lt;/h5&gt;&lt;p&gt;Everyone knows that global state is evil. The strongest argument against singletons is that they bring create global to an application. Depending on global state has consequences.&lt;/p&gt;&lt;p&gt;Suppose you have a singleton being used a multi-threaded application. A reasonable assumption is that the singleton object has to be thread-safe, i.e., it has to be able to be accessed by different threads without misbehaving. That’s not completely necessary.&lt;/p&gt;&lt;p&gt;One alternative is having a not-so-singleton object that has one instance per thread instead of one instance per process. This can be easily achieved with &lt;a href="http://en.wikipedia.org/wiki/Thread-local_storage" target="_blank"&gt;thread-local storage&lt;/a&gt;, which is supported by most programming languages. Even though these thread-local singletons are not valid to every problem, they are the easiest and safest way to have a thread-safe singleton.&lt;/p&gt;&lt;p&gt;We can go deeper on the idea of multi-instance-singletons (by the way, the term “singleton” might not be appropriate at this point, but that’s just a matter of naming). In many cases, what you really need is one instance per “context” or “call”, or whatever. A nice .NET example is on the &lt;code&gt;System.Web.HttpContext&lt;/code&gt; class. It has a static property called &lt;code&gt;Current&lt;/code&gt; that return an &lt;code&gt;HttpContext&lt;/code&gt;. This might not be commonly seen as an use of the singleton pattern, but it’s a very close variation. The way I see it, it’s basically a singleton that has one instance per http request.&lt;/p&gt;&lt;p&gt;Controlling the life cycle of “singleton” instances in these complex situations can be too complicated, and too specific to still be considered a pattern. That’s not actually a problem. I’ll get back to the subject later.&lt;/p&gt;&lt;h5&gt;- Abstraction and Decoupling&lt;/h5&gt;&lt;p&gt;Now, I want to expose a different facet of the pattern under discussion. Usually (at least in my code), the exposed type of the singleton instance is more abstract than its actual concrete type. Something like the C# code below.&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;readonly&lt;/span&gt; IAbstractThing Instance = &lt;span class="kwrd"&gt;new&lt;/span&gt; ConcreteThing();&lt;/pre&gt;&lt;p&gt;You may reasonably argue that this is not&amp;#160; a good usage of OO. If &lt;code&gt;IAbstractThing&lt;/code&gt; were destined to have only one concrete implementation, then you wouldn’t even need the interface to start with. But, in real world applications, that’s commonly not the case.&lt;/p&gt;&lt;p&gt;Exposing an abstract type opens some possibilities. You could, initially, delegate the responsibility of creating the instance to another component. By doing that, you achieve more than one advantage. You are now close to being able to create mock objects for unit testing. A secondary (or should I say primary?) advantage is better decoupling. The component that exposes the instance does not depend on any concrete implementations anymore, i.e., there will be one less dependency around&lt;/p&gt;&lt;p&gt;A group of components that work in this way (one component exposes an abstract object, and another creates the object) has dependency injection in it, even if no DI framework was used.&lt;/p&gt;&lt;h5&gt;- Dependency Injection&lt;/h5&gt;&lt;p&gt;Of course, the more sophisticated you get, the farther you get from the original pattern. All the intermediary variations are valid solutions for real problems. At each point, the decision of whether improve the code or not is a matter of balancing the costs of development (including test, support, etc.) with the actual advantages it will bring to the application.&lt;/p&gt;&lt;p&gt;The usual shortcut through such evolutionary process is a framework. And there is a lot of stable and dependable DI frameworks free for anyone to use. They are capable of providing a much more powerful solutions than any of the creational design patterns can, and at a lower cost. As I mentioned earlier, life cycle management might get very complex. Not with a good DI framework. Most of them support a broad range of extendable life cycle styles. By the way, my current favorite is &lt;a href="http://ninject.org/" target="_blank"&gt;Ninject&lt;/a&gt;. If you are a .NET programmer, I recommend that you give it a try.&lt;/p&gt;&lt;h4&gt;Final Remarks&lt;/h4&gt;&lt;p&gt;If you are building a non-trivial application and find yourself using a big mix of abstract factories, builders, prototypes, or whatever, be sure of one thing. You are in need for a good DI framework. Any language that has built-in DI, or has a built-in DI library, or enables such a library to be build, do not need to depend on “creational patterns”.&lt;/p&gt;&lt;p&gt;A similar statement can be made to other types of design patterns. Consider the &lt;a href="http://en.wikipedia.org/wiki/Strategy_pattern" target="_blank"&gt;strategy pattern&lt;/a&gt;, for example. It’s trivially implemented using &lt;a href="http://en.wikipedia.org/wiki/First-class_function" target="_blank"&gt;first-class functions&lt;/a&gt; (C#’s&amp;#160; anonymous methods). The &lt;a href="http://en.wikipedia.org/wiki/Observer_pattern" target="_blank"&gt;observer pattern&lt;/a&gt; can be effortlessly implemented with C# events. The &lt;a href="http://en.wikipedia.org/wiki/Iterator_pattern" target="_blank"&gt;iterator pattern&lt;/a&gt; can be graciously implemented with the &lt;code&gt;IEnumerable&lt;/code&gt; interface and some help from the &lt;code&gt;foreach&lt;/code&gt; keyword. Using the &lt;code&gt;yield return&lt;/code&gt; keyword, it’s possible to elegantly represent complex object interactions with a only a few lines of code.&lt;/p&gt;&lt;p&gt;Please, don’t get me wrong. Design patterns are good in many ways. For one thing, they provide a common vocabulary to programmers going through similar problems. What I’m saying is that they are generally misunderstood and overrated. Their ultimate purpose is to become invisible. Do not think design patterns are timeless. They aren’t. &lt;/p&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-594650338230686848?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/594650338230686848/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=594650338230686848&amp;isPopup=true' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/594650338230686848'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/594650338230686848'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2010/05/on-design-patterns-and-dependency.html' title='On Design Patterns and Dependency Injection'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-1458371947958266889</id><published>2010-03-15T18:57:00.008-03:00</published><updated>2010-03-15T19:11:29.262-03:00</updated><title type='text'>Lock-free Synchronization in C# 4 Events</title><content type='html'>If you're keeping yourself up-to-date with .NET Framework 4.0 and C# 4, you might have read &lt;a href="http://blogs.msdn.com/cburrows/archive/2010/03/05/events-get-a-little-overhaul-in-c-4-part-i-locks.aspx"&gt;"Events get a little overhaul in C# 4" series on Chris Burrows' blog&lt;/a&gt;. He's explaining some changes to the intrinsic implementation of events. They were introduced in C# 4, which is in RC now. One important detail is that there are &lt;b&gt;breaking changes&lt;/b&gt; included. So, you'd better get familiarized with that. If you haven't read his &lt;a href="http://blogs.msdn.com/cburrows/"&gt;latest posts&lt;/a&gt;, please, do it now.&lt;br /&gt;&lt;br /&gt;(intermission)&lt;br /&gt;&lt;br /&gt;Welcome back. If you are fond of details like me, you might've gotten curious about that "lock-free synchronization code" used to add (and remove) event handlers in C# 4. That's exactly what I intend to show here.&lt;br /&gt;&lt;br /&gt;The first step is simple. With a little help from Reflector, I disassembled the code generated for an simple event. After some variable renaming, here's what I've got:&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;private&lt;/span&gt; EventHandler dlgMyEvent;&lt;br /&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;event&lt;/span&gt; EventHandler MyEvent&lt;br /&gt;{&lt;br /&gt;    add&lt;br /&gt;    {&lt;br /&gt;        EventHandler valueBeforeCombine;&lt;br /&gt;        EventHandler valueBeforeAttribution = &lt;span class="kwrd"&gt;this&lt;/span&gt;.dlgMyEvent;&lt;br /&gt;        &lt;span class="kwrd"&gt;do&lt;/span&gt;&lt;br /&gt;        {&lt;br /&gt;            valueBeforeCombine = valueBeforeAttribution;&lt;br /&gt;            EventHandler newValue = (EventHandler) Delegate.Combine(valueBeforeCombine, &lt;span class="kwrd"&gt;value&lt;/span&gt;);&lt;br /&gt;            valueBeforeAttribution = Interlocked.CompareExchange&amp;lt;EventHandler&amp;gt;(&lt;span class="kwrd"&gt;ref&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.dlgMyEvent, newValue, valueBeforeCombine);&lt;br /&gt;        }&lt;br /&gt;        &lt;span class="kwrd"&gt;while&lt;/span&gt; (valueBeforeAttribution != valueBeforeCombine);&lt;br /&gt;    }&lt;br /&gt;    remove&lt;br /&gt;    {&lt;br /&gt;        &lt;span class="rem"&gt;// code ommitted (it's too similar to 'add')&lt;/span&gt;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;This code isn't obvious to understand (at least for me). I took quite some time to figure out what was happening. Of course, variables like &lt;code&gt;handler2&lt;/code&gt; and &lt;code&gt;handler3&lt;/code&gt; don't help much. I spared you from the trouble and renamed them.&lt;br /&gt;&lt;br /&gt;Looking carefully, the secret ingredient is the &lt;a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.compareexchange.aspx"&gt;&lt;code&gt;Interlocked.CompareExchange&lt;/code&gt;&lt;/a&gt;. Since most people are not familiar with this function (I wasn't), let me explain it. An equivalent implementation would be like the code below. There's a very important difference, though. The real one runs as an &lt;b&gt;atomic&lt;/b&gt; operation. &lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; T CompareExchange&amp;lt;T&amp;gt;(&lt;span class="kwrd"&gt;ref&lt;/span&gt; T location, T &lt;span class="kwrd"&gt;value&lt;/span&gt;, T comparand)&lt;br /&gt;{&lt;br /&gt;    var previousValue = location;&lt;br /&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (location == comparand) location = &lt;span class="kwrd"&gt;value&lt;/span&gt;;&lt;br /&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; previousValue;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now, we have everything needed to comprehend the idea behind of the new &lt;code&gt;event&lt;/code&gt; implementation. To make it crystal clear, let me expose it in human language. It goes like that:&lt;br /&gt;&lt;ol&gt;&lt;li&gt;Copy &lt;code&gt;this.dlgMyEvent&lt;/code&gt; into &lt;code&gt;valueBeforeCombine&lt;/code&gt;;&lt;/li&gt;&lt;li&gt;Create a new delegate called &lt;code&gt;newValue&lt;/code&gt; by combining &lt;code&gt;valueBeforeCombine&lt;/code&gt; with the supplied &lt;code&gt;value&lt;/value&gt;;&lt;/li&gt;&lt;li&gt;Atomically, verify that &lt;code&gt;dlgMyEvent&lt;/code&gt; is equal to &lt;code&gt;valueBeforeCombine&lt;/code&gt;, and overwrite &lt;code&gt;dlgMyEvent&lt;/code&gt; with &lt;code&gt;newValue&lt;/code&gt;;&lt;/li&gt;&lt;li&gt;If the overwrite didn't happen (i.e., &lt;code&gt;dlgMyEvent&lt;/code&gt; changed sometime between step &lt;b&gt;1&lt;/b&gt; and &lt;b&gt;3&lt;/b&gt;), go back to step &lt;b&gt;1&lt;/b&gt; and try everything again;&lt;/li&gt;&lt;/ol&gt;When I finally visualized this pattern, it felt like an &lt;a href="http://dictionary.reference.com/browse/epiphany"&gt;epiphany&lt;/a&gt;. As a computer scientist, I'm ashamed of not knowing it before. Now, I know it's called &lt;a href="http://en.wikipedia.org/wiki/Compare-and-swap"&gt;compare-and-swap&lt;/a&gt;. Obviously, it can be used a other scenarios, but all this is very low-level coding. So, kids, don't try this at home. :)&lt;br /&gt;&lt;br /&gt;I've a final comment. I decided to imitate MS and implemented a similar synchronization mechanism in my Custom Events. Here's the latest source &lt;a href="http://jplabscode.googlecode.com/files/JpLabs.CustomEvents_v1.5.zip"&gt;download link&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-1458371947958266889?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/1458371947958266889/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=1458371947958266889&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/1458371947958266889'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/1458371947958266889'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2010/03/lock-free-synchronization-in-c-4-events.html' title='Lock-free Synchronization in C# 4 Events'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-8899762386701637825</id><published>2010-01-12T11:46:00.004-02:00</published><updated>2010-01-12T13:34:23.899-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='extension methods'/><category scheme='http://www.blogger.com/atom/ns#' term='source code'/><title type='text'>My Extension Method Colllection</title><content type='html'>In addition to the small components I've shared in this blog, there's a lot of short functions that I've collected over time. Most of them are not interesting enough for a post of their own. Actually, I never seem to find a proper place to store this stuff. Until recently.&lt;br /&gt;&lt;br /&gt;I realized that most of these functions were already coded as extension methods. And the ones that weren't extension methods, could be refactored to be. So, I started to put all of them in a single assembly called JpLabs.Extensions.&lt;br /&gt;&lt;br /&gt;Some of this methods were extracted from sources like this &lt;a href="http://stackoverflow.com/questions/271398/what-are-your-favorite-extension-methods-for-c-net-codeplex-com-extensionover"&gt;question at SO&lt;/a&gt;, but the majority were written by me (or a co-worker) for direct use in other projects.&lt;br /&gt;&lt;br /&gt;The full source is available to download &lt;a href="http://jplabscode.googlecode.com/files/JpLabs.Extensions.zip"&gt;here&lt;/a&gt;. Feel free to use it as you see fit. All feedback is welcome.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-8899762386701637825?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/8899762386701637825/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=8899762386701637825&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/8899762386701637825'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/8899762386701637825'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2010/01/my-extension-method-colllection.html' title='My Extension Method Colllection'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-2749231025509361101</id><published>2010-01-07T11:02:00.011-02:00</published><updated>2010-01-12T14:36:44.673-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='iterator'/><category scheme='http://www.blogger.com/atom/ns#' term='c#'/><title type='text'>Iterators and Argument Validation</title><content type='html'>&lt;a href="http://msdn.microsoft.com/en-us/library/dscyy5s0.aspx"&gt;Iterators&lt;/a&gt; were introduced in C# 2.0, so they are not new. Before LINQ was born, I think most C# programmers had never seen an &lt;a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx"&gt;yield&lt;/a&gt; operator. I'm not sure when I saw it for the first time, but I certainly wasn't an early user. I still remember the puzzlement I felt trying to understand how this stuff works.&lt;br /&gt;&lt;br /&gt;If you ever opened the &lt;a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aspx"&gt;Enumerable&lt;/a&gt; class in Reflector you might have noticed that it has several nested private compiler-generated classes. This nested classes are generated whenever a class have iterator functions.&lt;br /&gt;&lt;br /&gt;The point I want to make in this post is about argument validation. I've seen in more than once people making a simplification that, IMHO, should be considered a defect in production code. As an example, consider the code below (which I extracted from an answer in stackoverflow).&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;br /&gt;    &lt;span class="kwrd"&gt;this&lt;/span&gt; IEnumerable&amp;lt;TFirst&amp;gt; first, IEnumerable&amp;lt;TSecond&amp;gt; second, Func&amp;lt;TFirst, TSecond, TResult&amp;gt; selector&lt;br /&gt;) {&lt;br /&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (first == &lt;span class="kwrd"&gt;null&lt;/span&gt;) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="str"&gt;"first"&lt;/span&gt;);&lt;br /&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (second == &lt;span class="kwrd"&gt;null&lt;/span&gt;) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="str"&gt;"second"&lt;/span&gt;);&lt;br /&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (selector == &lt;span class="kwrd"&gt;null&lt;/span&gt;) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="str"&gt;"selector"&lt;/span&gt;);&lt;br /&gt;    &lt;br /&gt;    &lt;span class="kwrd"&gt;using&lt;/span&gt; (var enum1 = first.GetEnumerator())&lt;br /&gt;    &lt;span class="kwrd"&gt;using&lt;/span&gt; (var enum2 = second.GetEnumerator())&lt;br /&gt;    &lt;span class="kwrd"&gt;while&lt;/span&gt; (enum1.MoveNext() &amp;amp;&amp;amp; enum2.MoveNext())&lt;br /&gt;    &lt;span class="kwrd" &gt;yield&lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; selector(enum1.Current, enum2.Current);&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;It's quite simple and it might be hard to find any issues even after reading it carefully. It will even pass through positive testing. The problem only appears when you try to send a &lt;code&gt;null&lt;/code&gt; value to any of the three parameters. As you may know, the code of an iterator function is not executed right after the call. It's executed only when the &lt;code&gt;IEnumerable&lt;/code&gt; is enumerated. This behavior is called delayed execution. Because of that, when a &lt;code&gt;null&lt;/code&gt; argument is passed, the &lt;code&gt;ArgumentNullException&lt;/code&gt; won't be thrown until the enumeration of the returned value. This is highly undesirable.&lt;br /&gt;&lt;br /&gt;Fortunately, there's a very simple way to avoid the problem. As mentioned in MSDN community content in this &lt;a href="http://msdn.microsoft.com/en-us/library/65zzykke.aspx"&gt;page&lt;/a&gt;, you should break the iterator function in two functions. Like this:&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;TResult&amp;gt; Zip&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;br /&gt;    &lt;span class="kwrd" style="font-weight:900;color:OrangeRed;"&gt;this&lt;/span&gt; IEnumerable&amp;lt;TFirst&amp;gt; first, IEnumerable&amp;lt;TSecond&amp;gt; second, Func&amp;lt;TFirst, TSecond, TResult&amp;gt; selector&lt;br /&gt;) {&lt;br /&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (first == &lt;span class="kwrd"&gt;null&lt;/span&gt;) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="str"&gt;"first"&lt;/span&gt;);&lt;br /&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (second == &lt;span class="kwrd"&gt;null&lt;/span&gt;) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="str"&gt;"second"&lt;/span&gt;);&lt;br /&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (selector == &lt;span class="kwrd"&gt;null&lt;/span&gt;) &lt;span class="kwrd"&gt;throw&lt;/span&gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; ArgumentNullException(&lt;span class="str"&gt;"selector"&lt;/span&gt;);&lt;br /&gt;    &lt;br /&gt;    &lt;span class="kwrd" style="font-weight:900;color:OrangeRed;"&gt;return&lt;/span&gt; Zip(first, second, selector);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span class="kwrd" style="font-weight:900;color:OrangeRed;"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; IEnumerable&amp;lt;TResult&amp;gt; ZipIterator&amp;lt;TFirst, TSecond, TResult&amp;gt;(&lt;br /&gt;    IEnumerable&amp;lt;TFirst&amp;gt; first, IEnumerable&amp;lt;TSecond&amp;gt; second, Func&amp;lt;TFirst, TSecond, TResult&amp;gt; selector&lt;br /&gt;) {&lt;br /&gt;    &lt;span class="kwrd"&gt;using&lt;/span&gt; (var enum1 = first.GetEnumerator())&lt;br /&gt;    &lt;span class="kwrd"&gt;using&lt;/span&gt; (var enum2 = second.GetEnumerator())&lt;br /&gt;    &lt;span class="kwrd"&gt;while&lt;/span&gt; (enum1.MoveNext() &amp;amp;&amp;amp; enum2.MoveNext())&lt;br /&gt;    &lt;span class="kwrd" style="font-weight:900;color:OrangeRed;"&gt;yield&lt;/span&gt; &lt;span class="kwrd" style="font-weight:900;color:OrangeRed;"&gt;return&lt;/span&gt; selector(enum1.Current, enum2.Current);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;I highlighted the key points. Notice that only the second function is an iterator, and it's private. The only place where it should be called is in the first function.&lt;br /&gt;&lt;br /&gt;By the way, &lt;code&gt;Zip&lt;/code&gt; is an extension method added in .NET 4.0. If you want to read more about &lt;code&gt;Zip&lt;/code&gt; and the elusive behavior of exceptions in iterator functions, I recommend this two posts:&lt;br /&gt;&lt;br /&gt;- Bart's LINQ's new Zip operator at &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx"&gt;http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx&lt;/a&gt;;&lt;br /&gt;&lt;br /&gt;- Eric's Zip Me Up at &lt;a href="http://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx"&gt;http://blogs.msdn.com/ericlippert/archive/2009/05/07/zip-me-up.aspx&lt;/a&gt;;&lt;br /&gt;&lt;br /&gt;- Eric's High maintenance at &lt;a href="http://blogs.msdn.com/ericlippert/archive/2008/09/08/high-maintenance.aspx"&gt;http://blogs.msdn.com/ericlippert/archive/2008/09/08/high-maintenance.aspx&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-2749231025509361101?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/2749231025509361101/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=2749231025509361101&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/2749231025509361101'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/2749231025509361101'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2010/01/iterators-and-argument-validation.html' title='Iterators and Argument Validation'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-987990366765750434</id><published>2009-07-30T10:03:00.018-03:00</published><updated>2009-11-17T18:03:54.414-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='immutability'/><category scheme='http://www.blogger.com/atom/ns#' term='c#'/><category scheme='http://www.blogger.com/atom/ns#' term='events'/><category scheme='http://www.blogger.com/atom/ns#' term='code samples'/><category scheme='http://www.blogger.com/atom/ns#' term='concurrency'/><title type='text'>Enhanced Weak Events Part  Two - Immutable Event Entry List</title><content type='html'>&lt;span style="font-weight:bold;"&gt;Posts in this series&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;- &lt;a href="http://jp-labs.blogspot.com/2009/07/enhanced-weak-events-part-one.html"&gt;Part One: DynamicMethod vs. Expression Tree Compilation&lt;/a&gt;&lt;br /&gt;- Part Two: Immutable Event Entry List (this post)&lt;br /&gt;- Part Three: Synchronized Events (to be written)&lt;br /&gt;- Part Four: Custom Events and unsolved problems (to be written)&lt;br /&gt;- Dynamic Code Generation With Lambda Expressions (to be written)&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;C# Events - Basics&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Just for a start, let me reinforce some preliminary definitions in an very factual way.&lt;br /&gt;&lt;ul&gt;&lt;li/&gt;&lt;span style="font-weight:bold;"&gt;Delegates&lt;/span&gt; are tuples composed by a reference &lt;span style="font-weight:bold;"&gt;(A)&lt;/span&gt; to a method, and a reference &lt;span style="font-weight:bold;"&gt;(B)&lt;/span&gt; to a target object.&lt;br /&gt;- All delegates are made immutable;&lt;br /&gt;- The reference &lt;span style="font-weight:bold;"&gt;(B)&lt;/span&gt; will be null if the method is static;&lt;br /&gt;- When a delegate is invoked, the referenced method is called. If the method is an instance method, the target object reference is used;&lt;br /&gt;&lt;li/&gt;&lt;span style="font-weight:bold;"&gt;Multicast Delegates&lt;/span&gt; encapsulate a collection of delegates.&lt;br /&gt;- When invoked, all of its delegates are invoked in an unspecified order;&lt;br /&gt;- Multicast delegates can only be created by composition or decomposition. Composition is the merging of two delegates into a new multicast delegate. Decomposition is a subtraction of one delegate from another;&lt;br /&gt;- There's no such thing as an empty multicastdelegate. If a decomposition would create one, the result is &lt;code&gt;null&lt;/code&gt;;&lt;br /&gt;- For all purposes, a multicast delegate &lt;span style="font-weight:bold;"&gt;&lt;code&gt;is&lt;/code&gt;&lt;/span&gt; a delegate;&lt;br /&gt;&lt;li/&gt;&lt;span style="font-weight:bold;"&gt;C# Events&lt;/span&gt; are nothing more than a special type of property that have &lt;code&gt;add&lt;/code&gt; and &lt;code&gt;remove&lt;/code&gt; accessors instead of &lt;code&gt;get&lt;/code&gt; and &lt;code&gt;set&lt;/code&gt;.&lt;br /&gt;- Only events of a delegate type can be declared;&lt;br /&gt;- Due to the special accessors, only the class that owns the event can reset its value or invoke its delegate, if it's not null;&lt;br /&gt;- When &lt;code&gt;add&lt;/code&gt; is called, the current delegate is composed with the delegate that was provided;&lt;br /&gt;- Conversely, &lt;code&gt;remove&lt;/code&gt; does a decomposition;&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;C# Events - Not So Basics&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Having said that, let's dive deeper. When it comes to c# events, there are two interesting problems that can be easily overseen. The simpler one is that an event is always initialized with null, and they can always be decomposed to null later on. In other words, an event can be null at any time. Since it's not possible to invoke a null delegate (without causing a &lt;code&gt;NullReferenceException&lt;/code&gt;), any class that provides an event has be to sure that the event is not null before invoking it.&lt;br /&gt;&lt;br /&gt;The other problem appears in multithreaded applications. A thread might be &lt;code&gt;add&lt;/code&gt;ing or &lt;code&gt;remove&lt;/code&gt;ing an event handler while the event is in the middle of an invocation. This is a race situation, and has to be correctly handled. If you want to check a complete explanation on this subject, I recommend you to read Eric's post on &lt;a href="http://blogs.msdn.com/ericlippert/archive/2009/04/29/events-and-races.aspx"&gt;events and races&lt;/a&gt;.The generally recommended solution to both problems is the following pattern:&lt;br /&gt;&lt;pre class="csharpcode"&gt;var handler = &lt;span class="kwrd"&gt;this&lt;/span&gt;.MyEvent;&lt;br /&gt;&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;, eventArgs);&lt;/pre&gt;&lt;br /&gt;Now, let's move to main subject of this post.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Mutable Event Entry List&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;As you may already have noticed, my custom events were born from Daniel Grunwald's &lt;a href="http://www.codeproject.com/KB/cs/WeakEvents.aspx"&gt;WeakEvents&lt;/a&gt;. Internally, to represent each &lt;span style="font-style:italic;"&gt;event entry&lt;/span&gt;* he chose to use a &lt;code&gt;List&amp;lt;EventEntry&amp;gt;&lt;/code&gt;. Using regular a &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt; seems very convenient. It will make &lt;span style="font-weight:bold;"&gt;add&lt;/span&gt; and &lt;span style="font-weight:bold;"&gt;remove&lt;/span&gt; operations simple and quick to execute, but there is a downside. &lt;code&gt;List&amp;lt;T&amp;gt;&lt;/code&gt;'s are mutable.&lt;br /&gt;&lt;br /&gt;One of the major disadvantages of mutable objects appear on multithreaded applications. Consider the problems that I've introduced above. They apply to custom events too. Alas, that invocation pattern can't be used.&lt;br /&gt;&lt;br /&gt;One goo point is that even an empty WeakEvent will never be null, so we don't event-is-null problem. The concurrency problem, though, can't be avoided. As the event entry list is mutable, any access to it should be synchronized if we want to make the custom event thread-safe.&lt;br /&gt;&lt;br /&gt;Looking at Grunwald's code that makes the invocation of a &lt;code&gt;WeakEvent&lt;/code&gt;, I noticed that the entry list is copied to an array before invoking the entries. No locks are made. Is that enough? Unfortunately, the answer is no. Copying the list to an array is not an atomic operation. If the list is modified in the middle of the copy, things will probably get messy. Even if he had enclosed the copy in a &lt;code&gt;lock&lt;/code&gt; block, there would still be the performance problem caused by the copy itself.&lt;br /&gt;&lt;br /&gt;* An &lt;span style="font-style:italic;"&gt;event entry&lt;/span&gt; is an abstraction of an event handler delegate. Weak event entries, for example, serve the same purpose of a regular delegate. The sole difference being that it does &lt;span style="font-weight:bold;"&gt;not&lt;/span&gt; keep a strong reference to the target object.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Immutable Event Entry List&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Naturally, my suggestion is to use an immutable list to store event entries. By the way, as I mentioned in the beginning, all delegates are immutable. And regular c# events use immutable multicast delegates internally. There's probably a good reason they did it that way, and I don't see why custom events should differ. Let's consider some aspects of this decision.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li/&gt;&lt;span style="font-weight:bold;"&gt;Lower invocation overhead&lt;/span&gt;: There's no need to copy event entries before invoking them because the list does never change. All that's needed before the invoking is to read the current list object and store a reference to it in a local variable. If the event is changed by other thread, a new list will be created, but the invocation will be working on an untouched list object.&lt;br /&gt;&lt;br /&gt;The only possible problem may happen when an handler is removed, but an invocation is being made. The result is that the handler is invoked even after it has been removed from the event. Actually, this is a third interesting problem. The post from Eric Lippert (&lt;a href="http://blogs.msdn.com/ericlippert/archive/2009/04/29/events-and-races.aspx"&gt;events and races&lt;/a&gt;) that I've suggested earlier talks about this stuff too. If you read it, you'll see that my custom events  are actually imitating the exactly same behavior that regular c# events have.&lt;br /&gt;&lt;br /&gt;Unfortunately, there is also a trade-off involved. Add and remove operations will be inevitably slower. Each time they happen, a new list has to be created, and a partial copy of the current entries will be made. Personally, invoking performance has higher priority than adding or removing performance, so I think this trade-off is acceptable. If anyone disagrees, I'll be very happy to hear your thoughts.&lt;br /&gt;&lt;br /&gt;&lt;li/&gt;&lt;span style="font-weight:bold;"&gt;Thread-safety&lt;/span&gt;: Invoking an event when its entry list is immutable completely thread-safe without any need for locks. That's a great win.&lt;br /&gt;&lt;br /&gt;Add and remove, on the other hand, are not thread safe. I can say as an excuse that the mutable-list-approach is not thread-safe too. At least, I did not created a problem that was not there before.&lt;br /&gt;&lt;br /&gt;Looking at regular events, we can see that even they are not thread-safe when it comes to add and remove. Would the C# language team let so big a hole in the language? Of course not. The solution is hidden from the programmer's eyes. Whenever you declare a regular c# event, the compiler generates the two accessors (&lt;code&gt;add&lt;/code&gt; and &lt;code&gt;remove&lt;/code&gt;). Both of them are them decorated with this custom attribute:&lt;code&gt;[System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.Synchronized)]&lt;/code&gt;. You can make a test assembly and decompile it to see. Or you can read this old MSDN &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc163533.aspx"&gt;article&lt;/a&gt; too.&lt;br /&gt;&lt;br /&gt;So, in my opinion, locking should be avoided unless there's no alternative. In a reusable component (like custom events), it's preferable to let it be not thread-safe and free of locks than forcing an overhead that is not always required. A developer that uses your component should be able to use any synchronization mechanism he wants, and only if needed. Inside the .NET Framework, almost all collection implementations are not synchronized for this reason. Following the same pattern, I won't put any locks on my Custom Events. User developers should be aware of that, and put locks around add/remove it they need it.&lt;br /&gt;&lt;/ul&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Conclusion&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;In a world where multi-core processors are everywhere, multithreading and immutability are increasingly important. If you want to read more about immutability in C#, you might want to check &lt;a href="http://weblogs.asp.net/bleroy/archive/2008/01/16/immutability-in-c.aspx"&gt;this&lt;/a&gt; out.&lt;br /&gt;&lt;br /&gt;If you read this far, you probably are interested in events. A very extensive article you might want to read is on &lt;a href="http://www.codeproject.com/KB/cs/event_fundamentals.aspx"&gt;codeproject&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Finally, as usual, here is the download link for the latest version (v1.1) the my CustomEvents' &lt;a href="http://jplabscode.googlecode.com/files/JpLabs.CustomEvents%20v1.1.zip"&gt;source code&lt;/a&gt;. See ya!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-987990366765750434?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/987990366765750434/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=987990366765750434&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/987990366765750434'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/987990366765750434'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2009/07/enhanced-weak-events-part-two-immutable_30.html' title='Enhanced Weak Events Part  Two - Immutable Event Entry List'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-649624291431958572</id><published>2009-07-14T16:20:00.015-03:00</published><updated>2009-11-17T17:49:49.327-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambda expressions'/><category scheme='http://www.blogger.com/atom/ns#' term='c#'/><category scheme='http://www.blogger.com/atom/ns#' term='code samples'/><category scheme='http://www.blogger.com/atom/ns#' term='c# 3.5'/><title type='text'>Enhanced Weak Events Part One - DynamicMethod vs. Expression Tree Compilation</title><content type='html'>&lt;span style="font-weight:bold;font-size:larger;"&gt;Introduction / Background&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;In my &lt;a href="http://jp-labs.blogspot.com/2009/02/trackable-properties-with-weak-events.html"&gt;last post&lt;/a&gt; some months ago I showed a use case for &lt;span style="font-style:italic;"&gt;weak events*&lt;/span&gt;. Since then, I've ran into some other interesting event problems, and that gave me time to make some improvements over Daniel's code.&lt;br /&gt;* &lt;span style="font-size:smaller"&gt;If you're not familiar with the concept of weak events, I believe the best introduction you can find is &lt;a href="http://www.codeproject.com/KB/cs/WeakEvents.aspx"&gt;Daniel Grunwald's article&lt;/a&gt;.&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;font-size:larger;"&gt;Weak Events Enhancements Part One&lt;/span&gt;: &lt;span style="font-size:small"&gt;&lt;span style="font-style:italic;"&gt;Faster Forwarder Delegates&lt;/span&gt; / &lt;span style="font-style:italic;"&gt;DynamicMethod vs. Lambda Expression Compilation&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;The first improvement that I made is, in fact, the last that I've implemented. In Daniel's final solution (&lt;a href="http://www.codeproject.com/KB/cs/WeakEvents.aspx#heading0014"&gt;FastSmartWeakEvent&lt;/a&gt;), a forwarder method is compiled using &lt;code style="font-size:larger"&gt;System.Reflection.Emit.DynamicMethod&lt;/code&gt;. Although this is a very light way to generate code dynamically, it's very low level. Usually, the generating code is quite unreadable and very hard to debug, to modify or to extend. Daniel's first version, for example, had a type safety issue. I imagine that it was hard to find, and the solution is not obvious to understand (at least it wasn't obvious for me).&lt;br /&gt;&lt;br /&gt;For some time I was wondering if there was any higher level alternative to a raw DynamicMethod. The usual way to hide low level code is by encapsulating it inside a higher level framework. I don't remember how the idea came to me at the time, but I realized that .NET Framework 3.5 already contains what I was looking for: &lt;a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx"&gt;Expression Trees&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Expressions trees can be composed dynamically, and compiled to a delegate whenever they are ready. I tried it out, and developed a new &lt;code style="font-size:larger"&gt;WeakEventForwarderProvider&lt;/code&gt; class. The implementation details have several interesting catches. In fact, I think there are enough of them that I'll cover them in another post. Until then, feel free to check out the code. For now, I'll share the results that I've found.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Maintainability&lt;/span&gt;: Readability is a key feature of a maintainable code, but opinions might always diverge about it. It depends on coding style, and my style is somewhat unusual. Even though I admit the new code is not easy to read, I feel that it has improved a bit from the original; and there is still room for improvement. Debugging, on the other hand, has certainly been improved. The main reason for this is that the debugger is able to show any intermediate expression as nice programmer-readable strings. They can also be converted to string. So, it's much easier to know what is being generated.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Correctness&lt;/span&gt;: Using DynamicMethod, it's possible to generate any sequence of IL commands. One obvious advantage of this is a very high flexibility. The trade-off is that it's too easy to generate broken code. Expression trees work as middle ground solution. Its major restriction is that &lt;a href="http://en.wikipedia.org/wiki/Statement_%28programming%29"&gt;statements&lt;/a&gt; are not allowed inside expressions. Fortunately, that can be worked around, specially when generating small pieces of code (I promise to explain how in a future post). A great advantage expressions do provide is a very good validation at dynamic-code-generation-time. The type safety bug that leaked from Daniel's first version of WeakEvents was found and fixed very easily using expressions.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Compiling Performance&lt;/span&gt;: I knew that expression compilation uses DynamicMethod internally, so I took for granted that it would be slower to compile. Surprisingly enough, the results that I've measured were close to a tie. Sometimes it appeared that lambda compilation was faster. This is still puzzling to me.  While I don't find a good explanation, I'll let the topic open for discussion. My best guess is that the overhead that expression trees add is so much smaller than the overhead of emitting the code that, proportionately, the first can be disregarded.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Executing Performance&lt;/span&gt;: Code execution performance is a tricky subject. You can always try to tweak assembly code to make it faster. You can do it at IL level with DynamicMethod too. But that generally is a bad idea. To quote &lt;a href="http://en.wikipedia.org/wiki/Donald_Knuth"&gt;Donald Knuth&lt;/a&gt;, premature optimization is the root of all evil. I've found out that the expression tree compiler is quite good. My tests have shown that my expression-generated delegates were about &lt;span style="font-style:italic;"&gt;15% faster&lt;/span&gt; to execute than the ones that Daniel has got. That's better than I've expected.&lt;br /&gt;&lt;br /&gt;Performance-wise, I came to a conclusion that simply reinforces one of my software beliefs. A well-built framework will not make user code slower. Actually, some remarkable cases are capable to make user code even faster. In my opinion, instead of optimizing your code, find a good library or framework to do the job for you. If you can't find it, do not optimize. At least not now. Considering all aspects, my expression tree solution was very satisfactory. And it was fun to code too.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;font-size:larger;"&gt;Following Posts&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;These are the next posts that I'm planning to write on Weak Events:&lt;br /&gt;- Events Part Two: Immutable event entry list;&lt;br /&gt;- Events Part Three: Synchronized Events&lt;br /&gt;- Events Part Four: Custom Events and unsolved problems&lt;br /&gt;- Dynamic Code Generation With Lambda Expressions&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;font-size:larger;"&gt;Source Code&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Download Custom Events source code &lt;a href="http://jplabscode.googlecode.com/files/JpLabs.CustomEvents%20v1.1.zip"&gt;here (v1.1 @ 2008.07.31)&lt;/a&gt;. It contains stuff that I've not discussed yet. If you're eager to see it, feel free to delve into the code. See you soon (I hope :)).&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Updated at 2009.08.03&lt;/span&gt;: Source code link updated.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-649624291431958572?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/649624291431958572/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=649624291431958572&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/649624291431958572'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/649624291431958572'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2009/07/enhanced-weak-events-part-one.html' title='Enhanced Weak Events Part One - DynamicMethod vs. Expression Tree Compilation'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-2778184925986171113</id><published>2009-02-18T18:30:00.036-03:00</published><updated>2009-08-03T19:46:20.182-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c#'/><category scheme='http://www.blogger.com/atom/ns#' term='events'/><category scheme='http://www.blogger.com/atom/ns#' term='code samples'/><title type='text'>Trackable Properties with Weak Events</title><content type='html'>Coming back from a long period of silence, I'm posting a little piece of code that I used in a project of mine. Usually, I start by the problem that I was facing and them I move to the solution. This time, I'll try another path.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;TrackableValue&amp;lt;T&amp;gt;&lt;/span&gt; - a very short description &lt;br /&gt;&lt;br /&gt;TrackableValue is a generic class that encapsulates a "value" and provides an event that will fire every time this "value" is changed.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Inspiration&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;When I came with the basic idea of TrackableValue, I was learning WPF. More precisely, I was trying to get a grip on &lt;a href="http://msdn.microsoft.com/en-us/library/ms752914.aspx"&gt;Dependency Properties&lt;/a&gt;. This is a very complex concept to get used to straightaway. To be short, they are at the base of several of the main advantages of WPF. Stuff like data biding, animations, themes, styles, property inheritance through WPF trees, and others are only possible because of dependency properies.&lt;br /&gt;&lt;br /&gt;At a time, I saw the advantage of creating a lighter version of these super properties. There were 3 requirements that I was seeking to fulfill. One, it must not be dependant on the WPF assemblies or any other UI framework. Two, it must be trackable for changes. Three, it must use some kind of weak events (more on this later). Obviously, the code that I'm posting fulfills these requirements.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Motivation&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;One advantage of a value being trackable is that you can make a one-direction data binding. In a &lt;a href="http://en.wikipedia.org/wiki/Model-view-controller"&gt;Model-view-controller&lt;/a&gt;-based application, for example, binding between a model and a view is almost imperative. UI and binding are too often seen working together. Most UI frameworks already have support to binding and I don't intend to substitute that. I didn't want my component to be dependent on any UI. Also, it shouldn't be directly associated to binding. Data binding is just one possible usage of it.&lt;br /&gt;&lt;br /&gt;My purpose was simply to facilitate the task of creating solid value-changed events. Putting code on the setter method of a regular CLR property is a simple and very straightforward way to track changes on a property. So, what is the problem with this approach? The problem is that it does not favor composition. I'll explain.&lt;br /&gt;&lt;br /&gt;When you want to track changes from outside the class that owns such property, things start to get complicated. Generally, it's possible to make a subclass that overrides the property, but it's not a good policy to let it be the only way of extending your application. Essentially, I'm repeating the mantra &lt;a href="http://www.artima.com/lejava/articles/designprinciples4.html"&gt;"favor object composition over class inheritance"&lt;/a&gt;. I think TrackableValue is a fine attempt accomplish this. Also, it has the advantage of using weak events, which I'll explain later.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Class "interface"&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;I was never very fond of UML, so I prefer to show a class structure in pseudo-code than using a class diagram. Here's an interface-like description of TrackableValue:&lt;br /&gt;&lt;pre style="font-family: Courier New; font-size: 10pt; color: black; background: white;line-height: 1.0em;margin: 0px;"&gt;&lt;span style="color: blue;"&gt;public&lt;/span&gt; &lt;span style="color: blue;"&gt;sealed&lt;/span&gt; &lt;span style="color: blue;"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;TrackableValue&lt;/span&gt;&amp;lt;T&amp;gt;&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: gray;"&gt;///&lt;/span&gt;&lt;span style="color: green;"&gt; &lt;/span&gt;&lt;span style="color: gray;"&gt;&amp;lt;summary&amp;gt;&lt;/span&gt;&lt;span style="color: green;"&gt;Constructor&lt;/span&gt;&lt;span style="color: gray;"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: gray;"&gt;///&lt;/span&gt;&lt;span style="color: green;"&gt; &lt;/span&gt;&lt;span style="color: gray;"&gt;&amp;lt;param name=&amp;quot;owner&amp;quot;&amp;gt;&lt;/span&gt;&lt;span style="color: green;"&gt;The object that 'owns' the value, if any&lt;/span&gt;&lt;span style="color: gray;"&gt;&amp;lt;/param&amp;gt;&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public&lt;/span&gt; TrackableValue(&lt;span style="color: blue;"&gt;object&lt;/span&gt; owner);&lt;br /&gt;&amp;nbsp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: gray;"&gt;///&lt;/span&gt;&lt;span style="color: green;"&gt; &lt;/span&gt;&lt;span style="color: gray;"&gt;&amp;lt;summary&amp;gt;&lt;/span&gt;&lt;span style="color: green;"&gt;This is the actual value&lt;/span&gt;&lt;span style="color: gray;"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public&lt;/span&gt; T Value { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; &lt;span style="color: blue;"&gt;set&lt;/span&gt;; }&lt;br /&gt;&amp;nbsp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: gray;"&gt;///&lt;/span&gt;&lt;span style="color: green;"&gt; &lt;/span&gt;&lt;span style="color: gray;"&gt;&amp;lt;summary&amp;gt;&lt;/span&gt;&lt;span style="color: green;"&gt;This is the event that will be raised every time a new value is set&lt;/span&gt;&lt;span style="color: gray;"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public&lt;/span&gt; &lt;span style="color: blue;"&gt;event&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;EventHandler&lt;/span&gt;&amp;lt;ValueChangedEventArgs&amp;lt;T&amp;gt;&amp;gt; ValueChanged { &lt;span style="color: blue;"&gt;add&lt;/span&gt;; &lt;span style="color: blue;"&gt;remove&lt;/span&gt;; }&lt;br /&gt;&amp;nbsp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: gray;"&gt;///&lt;/span&gt;&lt;span style="color: green;"&gt; &lt;/span&gt;&lt;span style="color: gray;"&gt;&amp;lt;summary&amp;gt;&lt;/span&gt;&lt;span style="color: green;"&gt;This property is only used to set the 'sender' parameter to the event handler&lt;/span&gt;&lt;span style="color: gray;"&gt;&amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public&lt;/span&gt; &lt;span style="color: blue;"&gt;object&lt;/span&gt; Owner { &lt;span style="color: blue;"&gt;get&lt;/span&gt;; }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Now, an example. The code below is a simple class with a trackable property using a TrackableValue.&lt;br /&gt;&lt;br /&gt;&lt;pre style="font-family: Courier New; font-size: 10pt; color: black; background: white;line-height: 1.0em;margin: 0px;"&gt;&lt;span style="color: blue;"&gt;public&lt;/span&gt; &lt;span style="color: blue;"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;ClassWithTrackablePropery&lt;/span&gt;&lt;br /&gt;{&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;private&lt;/span&gt; &lt;span style="color: blue;font-weight:bold;"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;TrackableValue&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;double&lt;/span&gt;?&amp;gt; innerValue;&lt;br /&gt;&amp;nbsp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public&lt;/span&gt; ClassWithTrackablePropery()&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; innerValue = &lt;span style="color: blue;"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;TrackableValue&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;double&lt;/span&gt;?&amp;gt;(&lt;span style="color: blue;font-weight:bold;"&gt;this&lt;/span&gt;);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public&lt;/span&gt; &lt;span style="color: blue;"&gt;double&lt;/span&gt;? Value&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;get&lt;/span&gt; { &lt;span style="color: blue;"&gt;return&lt;/span&gt; innerValue.Value; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;set&lt;/span&gt; { innerValue.Value = &lt;span style="color: blue;"&gt;value&lt;/span&gt;; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;&amp;nbsp;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public&lt;/span&gt; &lt;span style="color: blue;"&gt;event&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;EventHandler&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af;"&gt;ValueChangedEventArgs&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;double&lt;/span&gt;?&amp;gt;&amp;gt; ValueChanged&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;add&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; { innerValue.ValueChanged += &lt;span style="color: blue;"&gt;value&lt;/span&gt;; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;remove&lt;/span&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { innerValue.ValueChanged -= &lt;span style="color: blue;"&gt;value&lt;/span&gt;; }&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;There isn't much to explain about it, but I would like to make a few remarks. First, observe that I've set the &lt;span style="font-style:italic;"&gt;innerValue&lt;/span&gt; member field to &lt;span style="font-style:italic;"&gt;readonly&lt;/span&gt;. That's because the actual instance of TrackableValue should not change for the lifetime of the instance of ClassWithTrackablePropery. Second, when instantiating the TrackableValue, I'm setting its &lt;span style="font-style:italic;"&gt;owner&lt;/span&gt; to &lt;span style="font-style:italic;"&gt;this&lt;/span&gt;. This way, the &lt;span style="font-style:italic;"&gt;sender&lt;/span&gt; parameter sent to event handlers will be the ClassWithTrackablePropery object that owns the value that changed. This might be useful in a code that uses this class.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Weak Events&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Last but not least, I would like to introduce the notion of weak events. Right now, you might think that my code is too simple and didn't even deserve to be posted here. I wouldn't blame you to have this opinion. I tell you that the really sexy part of TrackableValue is the use of weak events. Before showing what they are (if you don't know already), I'll bring out a situation.&lt;br /&gt;&lt;br /&gt;Suppose you have three components in an application: MyView, MyBackEndService, and MyController. MyController controls the application. It manages intances of MyBackEndService and MyView. MyBackEndService communicates with some external application and may change its state asynchronously. MyView is an windows forms window that shows the state of a MyBackEndService and lets the user execute some commands on it.&lt;br /&gt;&lt;br /&gt;Now, let's say that MyView signs up for an event on MyBackEndService in order to display state changes in the UI. This will create a strong reference in MyBackEndService to MyView. If the user closes the MyView window, it should dispose itself and be garbage collected later. Suppose MyView doesn't detach from the event on MyBackEndService, the reference from MyBackEndService to MyView would still exists. This would make MyView never to be garbage collected until MyBackEndService is disposed! How to solve this problem? Who will save us? Weak Events!&lt;br /&gt;&lt;br /&gt;Basically, the difference between a regular event and an weak event is that the former keeps strong references to the event handler delegates, while the latter uses &lt;a href="http://msdn.microsoft.com/en-us/library/system.weakreference.aspx"&gt;WeakReference&lt;/a&gt;. This solves the problem that I've described beautifully.&lt;br /&gt;&lt;br /&gt;WPF uses &lt;a href="http://msdn.microsoft.com/en-us/library/aa970850.aspx"&gt;WeakEvent Patterns&lt;/a&gt; for most of its event system. As I said, I didn't want to make TrackableValue dependable on WPF. Fortunately, there is an excellent alternative. I used &lt;a href="http://www.codeproject.com/KB/cs/WeakEvents.aspx"&gt;Weak Events&lt;/a&gt; from Daniel Grunwald. I strongly suggest reading his article if you are interested in the subject. I wouldn't be able to explain it better, so I won't try.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Conclusion&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Although the code that I'm sharing here seems pretty neat to me, I have some questions about it. For example, should it really be a &lt;span style="font-style:italic;"&gt;class&lt;/span&gt;, or should it be a &lt;span style="font-style:italic;"&gt;struct&lt;/span&gt; instead? Also, is there a better way to control the &lt;span style="font-style:italic;"&gt;sender&lt;/span&gt; parameter in the event handler (instead of using the Owner property)? What about a PreviewValueChanged event where some user code would be able to validate the change and, possibly, cancel it? If you have an opinion on these questions, I would be very happy to hear it.&lt;br /&gt;&lt;br /&gt;Finally, here is the download link for the &lt;a href="http://jplabscode.googlecode.com/files/JpLabs.TrackableValue%20plus%20CustomEvents%20v1.1.zip"&gt;source code (v1.1 @ 2009.08.03)&lt;/a&gt;. The zip file contains the WeakEvents source and, as usual, a demo project.&lt;br /&gt;&lt;br /&gt;Have a nice day!&lt;!-- Strategy pattern is Java. ConcreteStrategy objects can be represented as simple delegates in C#. --&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Updated at 2008.03.03&lt;/span&gt;: Source code link updated.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-2778184925986171113?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/2778184925986171113/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=2778184925986171113&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/2778184925986171113'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/2778184925986171113'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2009/02/trackable-properties-with-weak-events.html' title='Trackable Properties with Weak Events'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-6770957508923546369</id><published>2008-11-27T20:35:00.008-02:00</published><updated>2009-03-02T10:38:51.489-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambda expressions'/><category scheme='http://www.blogger.com/atom/ns#' term='c#'/><category scheme='http://www.blogger.com/atom/ns#' term='code samples'/><category scheme='http://www.blogger.com/atom/ns#' term='c# 3.0'/><title type='text'>Dynamic Lambda Expressions Using An Isolated AppDomain</title><content type='html'>&lt;span style="font-weight:bold;"&gt;Background&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;In August, I submitted a post about &lt;a href="http://jp-labs.blogspot.com/2008/08/lambda-expressions-and-differentiation.html"&gt;Lambda Expressions and Differentiation&lt;/a&gt;. There, I  told shortly about a dynamic compiler for lambda expressions using CodeDom. I've enhanced the compiler so that it now deserves a post of its own.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Introduction&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;I'll start with the original problem that I needed to solve. I wanted to make a console application that would accept lambda expressions wrote by the user, transform it in another lambda expression and show it. After some research, let me list some of the stuff that can or can't be done with .NET:&lt;ol&gt;&lt;li&gt;One can write a lambda expressions to a easily readable string (that is similar to C# code, but it's not compilable);&lt;/li&gt;&lt;li&gt;One can dynamically create lambda expressions using static functions of the &lt;a href="http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression_members.aspx"&gt;Expression&lt;/a&gt; class;&lt;/li&gt;&lt;li&gt;One &lt;span style="font-weight:bold;"&gt;cannot&lt;/span&gt; create (at least not directly) lambda expressions from a string containing valid C# code;&lt;/li&gt;&lt;li&gt;One can dynamically compile code using &lt;a href="http://msdn.microsoft.com/en-us/library/y2k85ax6.aspx"&gt;CodeDOM&lt;/a&gt;.&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;Due to feature #1, it's effortless to show the transformed lambda expressions to the user. Feature #2 is essential to the transformations that I intended to do, which was finding derivatives (please, read the &lt;a href="http://jp-labs.blogspot.com/2008/01/blah-blah-blah-static-public-expression.html"&gt;original post&lt;/a&gt; if you're interested).&lt;br /&gt;&lt;br /&gt;A major problem came along when I realized the fact #3. So, the source lambda expressions in the first versions of my little application were hard coded. After I finished the derivation part, I began searching for options to generate lambda expressions from user inputted strings.&lt;br /&gt;&lt;br /&gt;One alternative was to make a parser (or find on the web) that put together an expression using feature #2. The other alternative is to let the framework do it by dynamically compiling the code (feature #4). Since the second is promptly available and is much more reliable than any parser I could code, that's what I chose to use.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Dynamic Compilation&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Before I continue, let me state that I'll not get into the details about using CodeDOM. &lt;a href="http://www.west-wind.com/presentations/dynamicCode/DynamicCode.htm"&gt;Here&lt;/a&gt; is a much more detailed explanation. Also, although you can compile VB.NET too, I'll talk only about C# here, sorry.&lt;br /&gt;&lt;br /&gt;Basically, it works like this. You need the full text of one or more source code files (including usings, namespaces, classes, and so forth). Then, through a &lt;a href="http://msdn.microsoft.com/en-us/library/system.codedom.compiler.codedomprovider.aspx"&gt;CodeDomProvider&lt;/a&gt;, you can compile your code to an &lt;span style="font-weight:italic;"&gt;Assembly&lt;/span&gt;. The assembly can exist only in memory or it could be generated directly to a file. You can access and execute what is in the assembly by reflection.&lt;br /&gt;&lt;br /&gt;For my particular case, where I wanted to generate lambda expressions from a string, CodeDOM is too generic. So, I made a wrapper around it that compiles a lambda expression code string by filling the template below. Then, using reflection I executed DynamicFunc and forwarded the returned LambdaExpression.&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; &lt;span style="font-weight:bold;"&gt;$Using0$&lt;/span&gt;;&lt;br /&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; &lt;span style="font-weight:bold;"&gt;$Using1$&lt;/span&gt;;&lt;br /&gt;&lt;span class="rem"&gt;//...&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; &lt;span style="font-weight:bold;"&gt;$UsingN$&lt;/span&gt;;&lt;br /&gt;&lt;span class="kwrd"&gt;namespace&lt;/span&gt; JpLabs.DynamicCode.DynamicAssembly&lt;br /&gt;{&lt;br /&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; DynamicClass&lt;br /&gt;    {&lt;br /&gt;        &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; LambdaExpression DynamicFunc() {&lt;br /&gt;            &lt;span class="kwrd"&gt;return&lt;/span&gt; (Expression&amp;lt;&lt;span style="font-weight:bold;"&gt;$DelegateType$&lt;/span&gt;&amp;gt;)( &lt;span style="font-weight:bold;"&gt;$LambdaExpresion$&lt;/span&gt; );&lt;br /&gt;        }&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;This solution solved my problem, but it has some issues. First, it's slow. Actually, it is not nearly as fast as it could be. One could say that I'm using an elephant gun to kill a fox. It's possible to modify it to compile several expressions at once, but that was not the case. I needed to compiled expressions one by one as the user inputs it.&lt;br /&gt;&lt;br /&gt;The bigger issue is that, each time an expression is compiled, an assembly is generated. Unlike object instances, the memory of loaded types and assemblies can't be release. In fact, there's one way to do that, it's by unloading the entire &lt;a href="http://en.wikipedia.org/wiki/Application_Domain"&gt;application domain&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Cross AppDomain Dynamic Compilation&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;One application might use multiple domains for several reasons. But I believe nearly that all of them have to deal with one typical problem. Code in one domain cannot access data in other domain. So, they have to communicate in alternative ways. The two ways that are most straightforward are serialization and &lt;a href="http://en.wikipedia.org/wiki/.NET_Remoting"&gt;remoting&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;The data I wanted to cross between domains are lambda expresssions. Unfortunately, a LambdaExpression is not &lt;a href="http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx"&gt;Serializable&lt;/a&gt;. And remoting is not an option too. I need to be able to unload the compiler domain, and by doing this, all remoting objects would be released and the proxies would cease to work.&lt;br /&gt;&lt;br /&gt;I thought I had hit a impassable wall. But I found this &lt;a href="http://www.codeproject.com/KB/cs/ExpressionEval.aspx"&gt;article&lt;/a&gt; with a solution. It also uses multiple domains to dynamically compile code. If you read to this point, you will probably like to take a look there too.&lt;br /&gt;&lt;br /&gt;The idea somewhat crazy. .NET reflection allows you to access the &lt;a href="http://en.wikipedia.org/wiki/Common_Intermediate_Language"&gt;IL&lt;/a&gt; of a method. One can pack it into a Serializable class and send it to another domain. There, the method would be reconstructed using the IL. This can be accomplished with the semi-magic &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.aspx"&gt;DynamicMethod&lt;/a&gt; class. To let you understand its wonderful features, I'll quote MSDN remarks about it:&lt;br /&gt;&lt;q&gt;You can use the &lt;span style="font-weight:bold;"&gt;DynamicMethod&lt;/span&gt; class to generate and execute a method at run time, without having to generate a dynamic assembly and a dynamic type to contain the method. The executable code created by the just-in-time (JIT) compiler is reclaimed when the &lt;span style="font-weight:bold;"&gt;DynamicMethod&lt;/span&gt; object is reclaimed. Dynamic methods are the most efficient way to generate and execute small amounts of code.&lt;/q&gt;&lt;br /&gt;&lt;br /&gt;The input for a DynamicMethod is exactly what we have: the IL that came from the compiled code on the other domain. The output is a delegate to a newly created (and releasable) function. Since the function returns our so desired lambda expression, we just need to call it.&lt;br /&gt;&lt;br /&gt;Now, let me summarize the steps involved in this lambda expression compiler:&lt;ol&gt;&lt;li&gt;Create an AppDomain;&lt;/li&gt;&lt;li&gt;Instantiate a compiler (actually, a wrapper around CodeDOM) on the new AppDomain;&lt;/li&gt;&lt;li&gt;Compile the input string into an in-memory assembly using the template I've shown above;&lt;/li&gt;&lt;li&gt;Unload the compiler domain (or keep it for reuse and unload it later);&lt;/li&gt;&lt;li&gt;Extract the IL of the &lt;span style="font-weight:italic;"&gt;DynamicFunc&lt;/span&gt; method (please, refer to the template), and send it to the original domain;&lt;/li&gt;&lt;li&gt;Employ a DynamicMethod to get a delegate from the compiled IL;&lt;/li&gt;&lt;li&gt;Call the delegate and it shall return a LambdaExpression.&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Conclusion&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Here's an reliable way to dynamically compile code without requiring always more memory. To be honest, I did some improvements that I didn't mention above. To mention, I tried to make the compiler generic enough so that it could compile other stuff than lambda expression. I think you can simply extend the compiler to achieve that. Please, tell me if anyone of you get to the point of doing that. I'll even let you in a short future-possible-enhancements-list:&lt;ul&gt;&lt;li&gt;Extend compiler to compile other stuff than lambda expressions;&lt;/li&gt;&lt;li&gt;Improve the compiler so that it can compile a batch of code strips.&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;And, finally, the source code download link: &lt;a href="http://jplabscode.googlecode.com/files/Jp-Labs.DynamicCode_plus_Differentiation.zip"&gt;here&lt;/a&gt;. Of course, this source includes a test project for the compiler. And, of course, the test project is my Differentiator.&lt;br /&gt;&lt;br /&gt;Thanks!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-6770957508923546369?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/6770957508923546369/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=6770957508923546369&amp;isPopup=true' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/6770957508923546369'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/6770957508923546369'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2008/11/dynamic-lambda-expressions-using.html' title='Dynamic Lambda Expressions Using An Isolated AppDomain'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-834000838488568709</id><published>2008-09-11T16:27:00.016-03:00</published><updated>2009-01-05T17:36:06.917-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='linq'/><category scheme='http://www.blogger.com/atom/ns#' term='c#'/><category scheme='http://www.blogger.com/atom/ns#' term='c# 3.0'/><title type='text'>LINQ Source Code (or LINQ for .NET 2.0)</title><content type='html'>&lt;span style="font-weight:bold;"&gt;Background&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Recently, I had to make some enhancements in a large stabilised asp.net solution. As usual, I began testing some code in a new project as a small proof of concept. After I was done, I realized that the old code was made using VS 2005 (i.e., over .NET Framework 2.0) and my test code used a lot of LINQ (i.e., over .NET Framework 3.5). Since upgrading the solution was not allowed, my only option was to remove Linq from my code. Or maybe not.&lt;br /&gt;&lt;br /&gt;Using VS 2008, it's possible to use almost all the features of C# 3.0 even in a project targetting the 2.0 framework. The exception is Linq, because it inherently references extension functions that are only present in the 3.5 framework. Since I needed only &lt;span style="font-style:italic;"&gt;Where()&lt;/span&gt; and &lt;span style="font-style:italic;"&gt;Select()&lt;/span&gt;, I simply coded them and it worked just fine. I saw it was possible to write code for all the Linq to Objects extension methods. Better yet, I could aquire it from a more trustful source.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Linq to Objects Source Code&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;It's &lt;a href="http://weblogs.asp.net/scottgu/archive/2007/10/03/releasing-the-source-code-for-the-net-framework-libraries.aspx"&gt;publicly known&lt;/a&gt; that a good part of the .NET Framework source code is available for anyone to &lt;a href="http://www.codeplex.com/NetMassDownloader"&gt;download&lt;/a&gt;. Unfortunately, the code for Linq to Objects was not released yet. The alternative was to disassemble the assembly using &lt;a href="http://en.wikipedia.org/wiki/.NET_Reflector"&gt;.NET Reflector&lt;/a&gt; (I hope MS will not sue me for this). Anyway, as the code was not genuinely authored by me, I took special care of not using my namespace (JpLabs) in it.&lt;br /&gt;&lt;br /&gt;One thing that Reflector don't do is to simplify functions that use &lt;span style="font-style:italic;"&gt;yield return&lt;/span&gt;. Instead, it shows what is actually compiled, i.e., one compiler-generated iterator class for each function. These classes use state machines to control the iteretion. If you want to see how such a class looks like, try using Reflector. If you're not familiarised to &lt;span style="font-style:italic;"&gt;yield return&lt;/span&gt;, you might want to check this &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc163682.aspx"&gt;arcticle&lt;/a&gt;. I decompiled all the iterator functions in Linq to Objects manually.&lt;br /&gt;&lt;br /&gt;To make this post short, I would like to say that, in addition to the existent Linq extension functions, I've included some of my own, like &lt;span style="font-style:italic;"&gt;ForEach&lt;T&gt;(Action&lt;T&gt; action)&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Download&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;Download the full source &lt;a href="http://jplabscode.googlecode.com/files/JpLabs.Linq.zip"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style:italic;"&gt;[Update @2008.09.25]&lt;/span&gt;&lt;br /&gt;I've just found out that there is a project with the exactly the same purpose as the one in this post. And the authors are much more reliable than me. Check out the &lt;a href="http://www.albahari.com/nutshell/linqbridge.aspx"&gt;LINQBridge&lt;/a&gt; from the &lt;a href="http://www.albahari.com"&gt;Albahari&lt;/a&gt; brothers. As mine, their code is completely open and free for any use.&lt;br /&gt;&lt;br /&gt;Also, I would like to suggest the excellent free book on &lt;a href="http://www.albahari.com/threading/"&gt;Threading in C#&lt;/a&gt; on their web page. It's definitely the most complete and most readable source on this subject that I know of.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-834000838488568709?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/834000838488568709/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=834000838488568709&amp;isPopup=true' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/834000838488568709'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/834000838488568709'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2008/09/linq-source-code-or-linq-for-net-20.html' title='LINQ Source Code (or LINQ for .NET 2.0)'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-2436030951141535130</id><published>2008-08-14T16:50:00.009-03:00</published><updated>2010-01-18T10:26:24.332-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambda expressions'/><category scheme='http://www.blogger.com/atom/ns#' term='c#'/><category scheme='http://www.blogger.com/atom/ns#' term='code samples'/><category scheme='http://www.blogger.com/atom/ns#' term='c# 3.0'/><title type='text'>Lambda Expressions and Differentiation (continued)</title><content type='html'>Today, I made a presentation about the &lt;a href="http://jp-labs.blogspot.com/2008/01/blah-blah-blah-static-public-expression.html"&gt;first article&lt;/a&gt; that I've posted on this blog. Since then I did some improvements on the code.&lt;br /&gt;&lt;br /&gt;The one extra feature that I implemented was a parser for lambda expressions. One of the first things that I did when I started fiddling with lambda expression was trying to generate one from a string. To my disappointment, there's not such a feature included in the .NET Framework. So, I coded a humble one using CodeDom.&lt;br /&gt;&lt;br /&gt;I'm sharing the &lt;a href="http://jplabscode.googlecode.com/files/Jp-Labs.DynamicCode_plus_Differentiation.zip"&gt;last source&lt;/a&gt; code that I have. You're free to play with it with one condition. You have to share enhancements with me. :P&lt;br /&gt;&lt;br /&gt;Also, I would like to let a challenge here. If you want to learn Lambda Expressions and don't have an idea to implement, try making code to &lt;span style="font-weight:bold;"&gt;simplify&lt;/span&gt; a &lt;a href="http://en.wikipedia.org/wiki/Polynomial"&gt;polynomial function&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Finally, as always, please, let your comment here.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-2436030951141535130?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/2436030951141535130/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=2436030951141535130&amp;isPopup=true' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/2436030951141535130'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/2436030951141535130'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2008/08/lambda-expressions-and-differentiation.html' title='Lambda Expressions and Differentiation (continued)'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-2996361826183383270</id><published>2008-08-08T09:51:00.006-03:00</published><updated>2009-01-05T17:28:27.383-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='MQ'/><category scheme='http://www.blogger.com/atom/ns#' term='middleware'/><category scheme='http://www.blogger.com/atom/ns#' term='c#'/><category scheme='http://www.blogger.com/atom/ns#' term='code samples'/><title type='text'>WebSphere MQ API (or MQAL)</title><content type='html'>&lt;a href="http://en.wikipedia.org/wiki/MQSeries"&gt;WebSphere MQ&lt;/a&gt; (or simply "MQ") is a messaging system made by IBM. If you've never used any message-oriented middleware, it might be a good idea to take a look at &lt;a href="http://en.wikipedia.org/wiki/Message_Oriented_Middleware"&gt;wikipedia&lt;/a&gt; first. Anyway, the basic problems that I had to solve in the component I'm posting are not specific to MOM systems. Thus, I hope you can extract some value from it in any case.&lt;br /&gt;&lt;br /&gt;So, let me introduce you to the problem. About one year ago, I had to develop an application that extensively uses MQ to exchange messages with other applications. This technology was kind of new to me and I had to learn the basics. To oversimplify, the idea is to connect to a &lt;span style="font-style:italic;"&gt;queue manager&lt;/span&gt;, then connect to a &lt;span style="font-style:italic;"&gt;queue&lt;/span&gt;, and finally put (or get) a &lt;span style="font-style:italic;"&gt;message&lt;/span&gt; to (or from) the &lt;span style="font-style:italic;"&gt;queue&lt;/span&gt;. The way that this process is made using the MQ API for .NET seemed very awkward to me. Then, I decided to write a component to encapsulate it and provide a simpler interface.&lt;br /&gt;&lt;br /&gt;Fisrt, I've tried to find a design pattern to fit the component in and I choosed to follow the way that database connections are handled in the .NET framework. Then, I've started to make some analogies. To start, a &lt;span style="font-style:italic;"&gt;queue manager connection&lt;/span&gt; could work pretty much like a &lt;span style="font-style:italic;"&gt;database connection&lt;/span&gt;. Both of them have parameters like server, port, user name, password, and database name / queue manager name. To summarize, here are some of the analogies I've made:&lt;br /&gt;- A &lt;span style="font-style:italic;"&gt;queue manager&lt;/span&gt; is like a &lt;span style="font-style:italic;"&gt;database&lt;/span&gt;;&lt;br /&gt;- A &lt;span style="font-style:italic;"&gt;queue manager connection&lt;/span&gt; is like a &lt;span style="font-style:italic;"&gt;database connection&lt;/span&gt;;&lt;br /&gt;- A &lt;span style="font-style:italic;"&gt;queue manager connection parameters&lt;/span&gt; is like a &lt;span style="font-style:italic;"&gt;database connection string&lt;/span&gt;;&lt;br /&gt;- A &lt;span style="font-style:italic;"&gt;queue&lt;/span&gt; is like a &lt;span style="font-style:italic;"&gt;table&lt;/span&gt; (or a &lt;span style="font-style:italic;"&gt;view&lt;/span&gt;);&lt;br /&gt;- A &lt;span style="font-style:italic;"&gt;queue connection&lt;/span&gt; is like an &lt;span style="font-style:italic;"&gt;database command&lt;/span&gt;;&lt;br /&gt;- A &lt;span style="font-style:italic;"&gt;message&lt;/span&gt; is like a &lt;span style="font-style:italic;"&gt;table row&lt;/span&gt;;&lt;br /&gt;- A &lt;span style="font-style:italic;"&gt;put message action&lt;/span&gt; is like an &lt;span style="font-style:italic;"&gt;execute insert command&lt;/span&gt;;&lt;br /&gt;- A &lt;span style="font-style:italic;"&gt;get message action&lt;/span&gt; is like an &lt;span style="font-style:italic;"&gt;execute select and delete command&lt;/span&gt;;&lt;br /&gt;- A &lt;span style="font-style:italic;"&gt;browse message action&lt;/span&gt; is like an &lt;span style="font-style:italic;"&gt;execute select command&lt;/span&gt;.&lt;br /&gt;&lt;br /&gt;Ok, you must have gotten the general idea. I won't get in much detail here, but let me list some of the problems I had to solve in order to implement this:&lt;br /&gt;- Translating a &lt;span style="font-style:italic;"&gt;queue connection string&lt;/span&gt; into &lt;span style="font-style:italic;"&gt;queue manager connection parameters&lt;/span&gt;. I solved this by coding a connection string parser using regular expressions;&lt;br /&gt;- Implement &lt;span style="font-style:italic;"&gt;queue transactions&lt;/span&gt;. This wasn't a requisite at the time, but MQ provides transactions and I felt like I had to offer a way to use them;&lt;br /&gt;- Inherently use a &lt;span style="font-style:italic;"&gt;queue connection pool&lt;/span&gt; under the covers. The tests that I've made using the MQ API showed that it doesn't had a connection pool. I would had to either make the user of my component keep connections for longer (in order to avoid opening and closing them too frequently) or code a connection pool and let the user enjoy all its benefits. This was pretty interesting to do and probably deserves a post of itself. For now I'll let you with the source code.&lt;br /&gt;&lt;br /&gt;By the way, I didn't touched this code for awhile now and I see that I've let some items on a TODO list, so I won't say it's a final version. Anyway, it's running in a production environment somewhere for months and it have not failed once.&lt;br /&gt;&lt;br /&gt;Feel free to download the source code &lt;a href="http://jplabscode.googlecode.com/files/Jp.Labs.MQAL.v0.5.zip"&gt;here&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-2996361826183383270?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/2996361826183383270/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=2996361826183383270&amp;isPopup=true' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/2996361826183383270'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/2996361826183383270'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2008/08/websphere-mq-api-or-mqal.html' title='WebSphere MQ API (or MQAL)'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-6469848668769299754</id><published>2008-06-03T17:58:00.006-03:00</published><updated>2008-06-04T10:45:34.044-03:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='functional programming'/><category scheme='http://www.blogger.com/atom/ns#' term='F#'/><category scheme='http://www.blogger.com/atom/ns#' term='parallel extensions'/><category scheme='http://www.blogger.com/atom/ns#' term='concurrency'/><title type='text'>Microsoft Parallel Extensions CTP released</title><content type='html'>In the past years, evolution of computing is turning to the grounds of high level concurrecy. Processors are becoming faster by being multi-core, and not by having higher frequencies. The time is coming so that even simple programs will be concurrent too. Parallel programs are harder to code, harder to test and can cause pseudo-random bugs that can drive programmers crazy. The best solution for this, as to many problems, is a dependable library and/or language support.&lt;br /&gt;&lt;br /&gt;There are several types of problems that require specific solutions. Making a responsive UI, for instance. How many application have you seen that simply stay frozen while it's processing something? I've made some of them myself. And the programmer cannot be blamed, most projects don't have the time (and money) to invest on a responsive UI. The WPF framework solves this in a very neat way. Its interface engine is fully concurrent. But that's a subject for other post.&lt;br /&gt;&lt;br /&gt;Yesterday, Microsoft released another CTP of its Parallel Extensions (PFX) library. You may get the details at their &lt;a href="http://blogs.msdn.com/pfxteam/"&gt;blog&lt;/a&gt; or at &lt;a href="http://msdn.microsoft.com/concurrency"&gt;MSDN&lt;/a&gt;. In case you're not familiar with it, I'll give a short brief here. Basically, the library's comprehended by three parts:&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;- Task Parallel Library&lt;/span&gt;&lt;br /&gt;Provides some imperative ways to express parallelism. The simpler one is the Invoke method. It receives a set of actions in the form of delegates and executes them concurrently, returning after all the actions have completed. If you have a loop in which iterations may run in parallel, you can use the For or the ForEach methods. When the problem requires a little more elaboration, there's the Task system. It's a set of classes that works somewhat like what the ThreadPool class does, but with much greater flexibility and control.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;- PLINQ&lt;/span&gt;&lt;br /&gt;It's a implementation of LINQ that allows anyone to easily make declarative parallel queries. All it's needed is to transform the IEnumerable&amp;lt;t&amp;gt; into a IParallelEnumerable&amp;lt;t&amp;gt; using the AsParallel() extention method. It's not optimized yet, but it certainly can boost many applications with almost no code change.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;- Coordination Data Structures&lt;/span&gt;&lt;br /&gt;It has a group of synchronization classes that enhance those that currently exists in the framework. Also, there are some thread-safe collection classes. Coincidently, they've created a ConcurrentQueue class that serves the same purpose as the one I've posted!&lt;br /&gt;&lt;br /&gt;A detail that you can't avoid noticing in this framework is the extensive use of delegates. LINQ itself is based on delegates being passed to other functions. This type of construct is called a &lt;a href="http://en.wikipedia.org/wiki/Higher-order_function"&gt;higher-order function&lt;/a&gt;. Another construct that is present in PFX is the &lt;a href="http://en.wikipedia.org/wiki/Continuation"&gt;continuation&lt;/a&gt;. Also, there are recurrent remarks in its documentation about side-effects and why they have to be avoided. All these characteristics are usually associated with &lt;a href="http://en.wikipedia.org/wiki/Functional_programming"&gt;functional langagues&lt;/a&gt;. No surprise some of the samples are in &lt;a href="http://research.microsoft.com/fsharp/"&gt;F#&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Functional programming has lived almost only at the academic world, but its future looks different. It holds a lot of interesting and useful concepts. The disturbing part is that very few programmers really know these concepts. Do you know any skilled/experienced/old programmer that can't understand OO programming? Well, can you really understand functional programming? I don't. At least not yet.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-6469848668769299754?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/6469848668769299754/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=6469848668769299754&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/6469848668769299754'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/6469848668769299754'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2008/06/microsoft-parallel-extensions-ctp.html' title='Microsoft Parallel Extensions CTP released'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-280403186561285110</id><published>2008-04-25T17:04:00.023-03:00</published><updated>2009-01-05T17:40:56.441-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='c#'/><category scheme='http://www.blogger.com/atom/ns#' term='code samples'/><category scheme='http://www.blogger.com/atom/ns#' term='concurrency'/><title type='text'>A C# BlockingQueue</title><content type='html'>Ok, things didn't go as I planned, so I'll stop promising and start delivering. This time I'll share with you a code I've used before.&lt;br /&gt;&lt;br /&gt;The problem is quite simple and is not new: exchange messages between threads. One possible solution is message queuing, but it's too bulky to use inside a single process. The simplest way to make threads communicate is through shared variables, but it's obviously too simple.&lt;br /&gt;&lt;br /&gt;So, what kind of feature I was looking for? To begin with, it needed to be fast and light. Secondly, it had to work in a fire-and-forget fashion, i.e., I wanted a thread to be able to send a message (or task, job, whatever) to another thread and go on. Obviously, in order to such a thing to function, it would have to use some sort of internal buffer. So, it looked like what I needed was a thread-safe FIFO queue.&lt;br /&gt;&lt;br /&gt;All right, I could simply use a &lt;a href="http://msdn2.microsoft.com/en-us/library/7977ey2c.aspx"&gt;&lt;i&gt;Queue&amp;lt;t&amp;gt;&lt;/i&gt;&lt;/a&gt; and wrap its calls around a lock statement. Or, even easier, use a non-generic &lt;a href="http://msdn2.microsoft.com/en-us/library/system.collections.queue.aspx"&gt;&lt;i&gt;Queue&lt;/i&gt;&lt;/a&gt; and transform if by calling the &lt;a href="http://msdn2.microsoft.com/en-us/library/system.collections.queue.synchronized.aspx"&gt;&lt;i&gt;Queue.Synchronized()&lt;/i&gt;&lt;/a&gt; method. In both ways, we'd get a simply synchronized thread-safe queue.&lt;br /&gt;&lt;br /&gt;Is that all? Of course not. Suppose we have a &lt;a href="http://en.wikipedia.org/wiki/Producer-consumer_problem"&gt;producer-consumer problem&lt;/a&gt; to solve. Usually, when the buffer is empty, the consumer is supposed to idly wait for an new item. How could we accomplish that using a synched queue? If we try to dequeue from an empty &lt;i&gt;Queue&lt;/i&gt;, a exception is thrown.  We could check the item count before dequeueing, but there would be two steps involved and it wouldn't be thread-safe even if the &lt;i&gt;Queue&lt;/i&gt; instance is synched. Another possibility is catching the queue-is-empty exception, which is a very lousy trick. Anyway, we wouldn't be able to avoid writing synchronization code and this is not what I wanted.&lt;br /&gt;&lt;br /&gt;So, considering that you are introduced to the problem, let me show the wish list that I gathered in the form of an interface:&lt;pre class="csharpcode"&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IBlockingQueue&lt;br /&gt;{&lt;br /&gt;&lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;Max number of item in the queue (-1 means there's no limit)&amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;int&lt;/span&gt; MaxQueueDepth { get; }&lt;br /&gt;&lt;br /&gt;&lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;Returns false when there's something wrong, e.g., queue full&amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;bool&lt;/span&gt; TryEnqueue(&lt;span class="kwrd"&gt;object&lt;/span&gt; item);&lt;br /&gt;&lt;br /&gt;&lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;Returns false when there's no message to read&amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;bool&lt;/span&gt; TryDequeue(&lt;span class="kwrd"&gt;out&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; item);&lt;br /&gt;&lt;br /&gt;&lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;Returns false when a timeout or an abort happens&amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;bool&lt;/span&gt; WaitEnqueue(&lt;span class="kwrd"&gt;object&lt;/span&gt; item, &lt;span class="kwrd"&gt;int&lt;/span&gt; millisecondsTimeout, FuncGetVolatileFlag ExternalAbortSignaled);&lt;br /&gt;&lt;br /&gt;&lt;span class="rem"&gt;/// &amp;lt;summary&amp;gt;Returns false when a timeout or an abort happens&amp;lt;/summary&amp;gt;&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;bool&lt;/span&gt; WaitDequeue(&lt;span class="kwrd"&gt;out&lt;/span&gt; &lt;span class="kwrd"&gt;object&lt;/span&gt; item, &lt;span class="kwrd"&gt;int&lt;/span&gt; millisecondsTimeout, FuncGetVolatileFlag ExternalAbortSignaled);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;delegate&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; FuncGetVolatileFlag();&lt;/pre&gt;&lt;br /&gt;&lt;i&gt;TryDequeue()&lt;/i&gt; and &lt;i&gt;TryEnqueue&lt;/i&gt; are two simply synchronized methods to access the queue. The other two (&lt;i&gt;WaitDequeue()&lt;/i&gt; and &lt;i&gt;WaitEnqueue()&lt;/i&gt;) are much more interesting. The first one will try to dequeue and, if the queue is empty, will wait for a new item. The latter will try to enqueue and, if the queue is full, will wait until there's room for the new item.&lt;br /&gt;&lt;br /&gt;But that's still not enough. A common problem in a multithreaded application is when you need to close it and there are some threads still running. There's several possible approaches on how to close them. The safer choice might be to wait for every thread to end, but it might take too long. One alternative is to &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threading.thread.interrupt.aspx"&gt;terminate&lt;/a&gt; everyone, but it's very risky. I think the best pick is to ask somehow the threads to stop and &lt;a href="http://msdn2.microsoft.com/en-us/library/system.threading.thread.join.aspx"&gt;wait&lt;/a&gt; until they do so. With my blocking queue, you can choose between any of the 3.&lt;br /&gt;&lt;br /&gt;Let me explain how. As you can see, I've put two addicional parameters. Both have the same purpose: cancel the action and return the code execution to the client code. Whilst the fisrt is obviously a timeout, one might wonder what that other parameter is. It's a delegate of a type that accepts functions that like this:&lt;i&gt;bool func()&lt;/i&gt;. Its name is &lt;i&gt;ExternalAbortSignaled&lt;/i&gt; and its type name is &lt;i&gt;FuncGetVolatileFlag&lt;/i&gt;, so I hope it's not hard to recognize how it's used.&lt;br /&gt;&lt;br /&gt;In order to eliminate any doubts, I'll describe it. The idea is that, while waiting, the &lt;i&gt;ExternalAbortSignaled&lt;/i&gt; delegate will be called in short intervals. If it returns true at any time, the waiting ends and no item is enqueued/dequeued. Also the function returns false. In that way, it's possible to provide the queue an anonymous method that merely returns the value of a boolean flag. Whenever the flag is set to true, the wait function will return promptly and the application as a whole will be able to respond faster.&lt;br /&gt;&lt;br /&gt;As you may know, java has a built-in &lt;a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html"&gt;&lt;i&gt;BlockingQueue&lt;/i&gt;&lt;/a&gt; already. Sadly, java has direct support for delegates. So, I think it would be hard to code a functionality like an abort flag in an elegant way.&lt;br /&gt;&lt;br /&gt;Now, if you want to know what is the best way to implement the waiting synchronization code, I'll let the explanation to &lt;a href="http://www.albahari.com/threading/index.html"&gt;Joseph&lt;/a&gt;, which is much more eloquent than me. It might be a good idea to take a look at &lt;a href="http://groups.google.com/group/jp-labs/web/JpLabs.BlockingQueue.zip"&gt;my source code&lt;/a&gt; too. The technique that I've chosen is through &lt;a href="http://www.albahari.com/threading/part4.html#_Wait_and_Pulse"&gt;Wait and Pulse&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;Some ideas for future enhancements that I've thought of are:&lt;br /&gt;- TryPeek() and WaitPeek()&lt;br /&gt;- Transactions&lt;br /&gt;&lt;br /&gt;Source code download link at &lt;a href="http://jplabscode.googlecode.com/files/JpLabs.BlockingQueue.zip"&gt;google code&lt;/a&gt; &lt;!-- a href="http://www.mediafire.com/?ziu1d4ldxmn"&gt;mirror two&lt;/a --&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-style:italic;"&gt;[Updated at 2008-04-28]&lt;/span&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-280403186561285110?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/280403186561285110/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=280403186561285110&amp;isPopup=true' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/280403186561285110'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/280403186561285110'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2008/04/c-blockingqueue.html' title='A C# BlockingQueue'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-1907783676098399374</id><published>2008-02-19T11:36:00.001-03:00</published><updated>2008-02-19T11:38:17.184-03:00</updated><title type='text'>Hello, Again</title><content type='html'>I was on vacations until recently and I'm quite busy now, so it might take longer than I expected to write a new article. I guess it's a good thing to publish short posts once in a while.&lt;br /&gt;&lt;br /&gt;Anyway, what I wanted to tell you is that a group that I'm part of is organizing an event here in Porto Alegre. I'll make a presentation about LINQ to Relational Data. Very much of it is 'inspired' in material from &lt;a href="http://channel9.msdn.com/Showpost.aspx?postid=357689"&gt;Mike Pizzo&lt;/a&gt;, but I'll show some stuff of my own.&lt;br /&gt;&lt;br /&gt;Since I'm studing LINQ, I'm trying to prepare an interesting article about it. If you can't wait and want to get a deep dive into it, I can recomend a very exhaustive series of posts on &lt;a href="http://community.bartdesmet.net/blogs/bart/archive/2007/04/05/the-iqueryable-tales-linq-to-ldap-part-0.aspx"&gt;LINQ to LDAP&lt;/a&gt; by Bart De Smet's.&lt;br /&gt;&lt;br /&gt;See ya!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-1907783676098399374?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/1907783676098399374/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=1907783676098399374&amp;isPopup=true' title='4 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/1907783676098399374'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/1907783676098399374'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2008/02/hello-again.html' title='Hello, Again'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>4</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-8506750989297589664</id><published>2008-01-07T15:30:00.006-02:00</published><updated>2009-01-05T17:42:25.261-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='lambda expressions'/><category scheme='http://www.blogger.com/atom/ns#' term='c#'/><category scheme='http://www.blogger.com/atom/ns#' term='code samples'/><category scheme='http://www.blogger.com/atom/ns#' term='c# 3.0'/><title type='text'>Lambda Expressions and Higher-Order Functions</title><content type='html'>&lt;span style="font-style: italic;"&gt;[This article has a continuation &lt;a href="http://jp-labs.blogspot.com/2008/08/lambda-expressions-and-differentiation.html"&gt;here&lt;/a&gt;]&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;&lt;p&gt;First, I need to ask you not to be scare of the title I've chosen. Less than two months ago, I barely knew what the first name was and have never heard of the latter.&lt;br /&gt;&lt;br /&gt;As you might know, the brand-new C# 3.0 has support to &lt;a href="http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx"&gt;lambda expressions&lt;/a&gt;. You can imagine it as a less wordy way to describe anonymous delegates. A major difference between them is that a lambda expression doesn't necessarily needs to be compiled. In fact, it's just a representation of a function. In addition to being compiled, they can be serialized (if you want to pass it on), analyzed and even dynamically created at run-time. I'll be using the last two here.&lt;br /&gt;&lt;br /&gt;Now, let me introduce the computational (as well as mathematical) concept of a &lt;a href="http://en.wikipedia.org/wiki/Higher-order_function"&gt;higher-order funcion&lt;/a&gt; (aka operators in math). It's nothing more than a function that receives another function as a parameter and/or returns a function.&lt;br /&gt;&lt;br /&gt;Why would a function receive another function as a parameter? If you can't imagine a good answer or are just not convinced there's one, I suggest that you read &lt;a href="http://www.joelonsoftware.com/items/2006/08/01.html"&gt;this&lt;/a&gt; very didactic article (&lt;a href="http://diditwith.net/PermaLink,guid,a1a76478-03d2-428f-9db6-9cf4e300ea0f.aspx"&gt;this&lt;/a&gt; is also good). Anyway, you can implement such functions in c# 2.0 without problems. What I want to examine are functions that returns another functions. If you are not using c# 3.0 (or a functional language), you might find some difficulties. Basically, you would be limited to returning one of a set of pre-declared functions. You could try using &lt;a href="http://diditwith.net/PermaLink,guid,235646ae-3476-4893-899d-105e4d48c25b.aspx"&gt;closures&lt;/a&gt; or dynamic code generation to add some versatility, but it probably would be rather cumbersome.&lt;br /&gt;&lt;br /&gt;You may be asking why would anyone need such higher-order function. I will let this question open and focus on how to implement it. I was searching for a good example and can't imagine a better one than the differentiation, i.e., the mathematical process of obtaining the &lt;a href="http://mathworld.wolfram.com/Derivative.html"&gt;derivative&lt;/a&gt; of a function.&lt;br /&gt;&lt;br /&gt;So, I'll build a functional that receives a f(x) and return a f'(x). The declaration of this in c# would be like that:&lt;br /&gt;&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; Expression&amp;lt;Func&amp;lt;&lt;span class="kwrd"&gt;double&lt;/span&gt;,&lt;span class="kwrd"&gt;double&lt;/span&gt;&amp;gt;&amp;gt; Differentiate(&lt;span class="kwrd"&gt;this&lt;/span&gt; Expression&amp;lt;Func&amp;lt;&lt;span class="kwrd"&gt;double&lt;/span&gt;,&lt;span class="kwrd"&gt;double&lt;/span&gt;&amp;gt;&amp;gt; f)&lt;br /&gt;{&lt;br /&gt;&lt;span class="rem"&gt;//I will find the derivative of f with respect to the variable x (it's the 1st and sole parameter)&lt;/span&gt;&lt;br /&gt;ParameterExpression x = f.Parameters[0];&lt;br /&gt;&lt;br /&gt;&lt;span class="rem"&gt;//Diff is the function that actually does the differentiation&lt;/span&gt;&lt;br /&gt;Expression derivative = Diff(f.Body, x);&lt;br /&gt;&lt;br /&gt;&lt;span class="rem"&gt;//Build a new lambda expression with the derivative expression body&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;return&lt;/span&gt; Expression.Lambda&amp;lt;Func&amp;lt;&lt;span class="kwrd"&gt;double&lt;/span&gt;,&lt;span class="kwrd"&gt;double&lt;/span&gt;&amp;gt;&amp;gt;(derivative, f.Parameters);&lt;br /&gt;}&lt;/pre&gt;*Func&amp;lt;double,double&amp;gt; is a delegate type for functions that receives a single double parameter and returns a double. Expression&amp;lt;Func&amp;lt;double,double&amp;gt;&amp;gt; is the type of a lambda expression that represents a Func&amp;lt;double,double&amp;gt; function.&lt;br /&gt;&lt;br /&gt;As you can see I used a Diff function that actually calculates the derivative. How does it work? It needs to analyze the original expression and create a new expression that represents its derivative. Luckily enough, this calculation can be done recursively using a set a rules. Let's start with the sum rule: namely, derivatives of sums are equal to the sum of derivatives. Coding that in c# 3.0 is easier than you one might thought. Look:&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; Expression Diff(Expression exp, ParameterExpression dx)&lt;br /&gt;{&lt;br /&gt;&lt;span class="kwrd"&gt;switch&lt;/span&gt; (exp.NodeType) {&lt;br /&gt;&lt;span class="kwrd"&gt;case&lt;/span&gt; ExpressionType.Add: {&lt;br /&gt;BinaryExpression f = (BinaryExpression)exp;&lt;br /&gt;&lt;span class="rem"&gt;//Sum rule: [g(x) + h(x)]' == g'(x) + h'(x).&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;return&lt;/span&gt; Expression.Add( &lt;span class="rem"&gt;//Create an add expression&lt;/span&gt;&lt;br /&gt;   Diff(f.Left, dx),  &lt;span class="rem"&gt;//g'(x) +&lt;/span&gt;&lt;br /&gt;   Diff(f.Right, dx)  &lt;span class="rem"&gt;//h'(x)&lt;/span&gt;&lt;br /&gt;);&lt;br /&gt;}&lt;br /&gt;&lt;span class="rem"&gt;/* other cases omitted ... */&lt;/span&gt;&lt;br /&gt;}&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;In similar ways, we can implement the other recursive rules (such as the &lt;a href="http://mathworld.wolfram.com/ProductRule.html"&gt;product rule&lt;/a&gt;, the &lt;a href="http://mathworld.wolfram.com/QuotientRule.html"&gt;quotient rule&lt;/a&gt;, the &lt;a href="http://mathworld.wolfram.com/PowerRule.html"&gt;power rule&lt;/a&gt;, etc). However, any recursion need a stop condition. We'll have two stop conditions: for constants, which derivative is zero; and for the variable x, which derivative is one. The code looks like this:&lt;br /&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;case&lt;/span&gt; ExpressionType.Parameter: {&lt;br /&gt;&lt;span class="rem"&gt;//be aware that f(x) = y is a constant with respect to x&lt;/span&gt;&lt;br /&gt;&lt;span class="kwrd"&gt;return&lt;/span&gt; (exp == dx) ? Expression.Constant(1d) : Expression.Constant(0d);&lt;br /&gt;}&lt;br /&gt;&lt;span class="kwrd"&gt;case&lt;/span&gt; ExpressionType.Constant: {&lt;br /&gt;&lt;span class="kwrd"&gt;return&lt;/span&gt; Expression.Constant(0d);&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;There's also the &lt;a href="http://mathworld.wolfram.com/ChainRule.html"&gt;chain rule&lt;/a&gt;, that is quite trickier to implement. I did it with very little code, though. As you're not faint of heart, take a look at my &lt;a href="http://jplabscode.googlecode.com/files/Jp-Labs.DynamicCode_plus_Differentiation.zip"&gt;full source&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;And that's all for the day, folks. Please, comment.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-8506750989297589664?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/8506750989297589664/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=8506750989297589664&amp;isPopup=true' title='6 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/8506750989297589664'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/8506750989297589664'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2008/01/blah-blah-blah-static-public-expression.html' title='Lambda Expressions and Higher-Order Functions'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>6</thr:total></entry><entry><id>tag:blogger.com,1999:blog-5325631863209472986.post-6709872018086163645</id><published>2008-01-04T12:56:00.000-02:00</published><updated>2008-01-07T13:32:52.799-02:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='introduction'/><title type='text'>Hello World</title><content type='html'>Hi,&lt;br /&gt;&lt;br /&gt;My name is João Paulo Bochi and I'm a senior programmer in Brazil. Welcome to my knowledge sharing blog.&lt;br /&gt;&lt;br /&gt;I'll post mainly C# related stuff with tips and tricks that I learned. I plan to include topics about C#, LINQ, ASP.NET, AJAX, Concurrent Programming and some others I am (or might get) interested with.&lt;br /&gt;&lt;br /&gt;Please, pay a visit soon.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/5325631863209472986-6709872018086163645?l=jp-labs.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://jp-labs.blogspot.com/feeds/6709872018086163645/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://www.blogger.com/comment.g?blogID=5325631863209472986&amp;postID=6709872018086163645&amp;isPopup=true' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/6709872018086163645'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/5325631863209472986/posts/default/6709872018086163645'/><link rel='alternate' type='text/html' href='http://jp-labs.blogspot.com/2008/01/hello-world.html' title='Hello World'/><author><name>jpbochi</name><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='16' height='16' src='http://img2.blogblog.com/img/b16-rounded.gif'/></author><thr:total>0</thr:total></entry></feed>
