<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Technical Issues &#38; Solutions</title>
	<atom:link href="http://bembengarifin.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://bembengarifin.wordpress.com</link>
	<description>Bembeng Arifin's Ramblings</description>
	<lastBuildDate>Wed, 04 Jan 2012 10:06:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='bembengarifin.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Technical Issues &#38; Solutions</title>
		<link>http://bembengarifin.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://bembengarifin.wordpress.com/osd.xml" title="Technical Issues &#38; Solutions" />
	<atom:link rel='hub' href='http://bembengarifin.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Generate Func by using Expression Trees</title>
		<link>http://bembengarifin.wordpress.com/2011/11/08/generate-func-by-using-expression-trees/</link>
		<comments>http://bembengarifin.wordpress.com/2011/11/08/generate-func-by-using-expression-trees/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 16:19:10 +0000</pubDate>
		<dc:creator>Bembeng Arifin</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Expression Trees]]></category>

		<guid isPermaLink="false">http://bembengarifin.wordpress.com/?p=361</guid>
		<description><![CDATA[I stumbled in a code change today which involved some value look-up in a dictionary based on some property name which is by convention (paramA + paramB + &#8220;property&#8221;). So there was used to be a pre-calculated sum stored in the dictionary by a user control. Now, I need to rely on the underlying data [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=361&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I stumbled in a code change today which involved some value look-up in a dictionary based on some property name which is by convention (paramA + paramB + &#8220;property&#8221;).</p>
<p>So there was used to be a pre-calculated sum stored in the dictionary by a user control.</p>
<p><pre class="brush: csharp;">
class SomeClass
{
    public Decimal DailyFunctionalAmount { get; set; }
    public Decimal MonthToDateFunctionalAmount { get; set; }
    ///..... have much more here
}

Decimal GetTotal(String fieldName, IDictionary&lt;String, Decimal&gt; lookups)
{
    // used to be as simple as getting the pre-calculated sum via dictionary (populated somewhere else by control)
    var totalByLookup = lookups[fieldName];
    return totalByLookup;
}
</pre></p>
<p>Now, I need to rely on the underlying data rows to calculate the sum.</p>
<p><pre class="brush: csharp;">
var lists = new List&lt;SomeClass&gt; {
    new SomeClass { DailyFunctionalAmount = 10, MonthToDateFunctionalAmount = 100},
    new SomeClass { DailyFunctionalAmount = 10, MonthToDateFunctionalAmount = 100},
};

// I could not use the following code as this is compiled/pre-determined code where we actually need the selector in run-time based on the generated property name by convention
var totalByLinq = lists.Sum(r =&gt; r.DailyFunctionalAmount); 
</pre></p>
<p>Luckily, there is this <a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx" target="blank">expression trees</a> which seems to be perfect for the job, rather than a nasty static function returning selector based on possible combinations for the property name by convention.</p>
<p><pre class="brush: csharp;">
// returns -&gt; dtoType =&gt; dtoType.propertyName
Func&lt;SomeClass, Decimal&gt; GetMyFunc(string propertyName)
{
    var dtoTypeParameter = Expression.Parameter(typeof(SomeClass), &quot;dtoType&quot;);
    var dtoPropertySelector = Expression.Property(dtoTypeParameter, propertyName);
    var lamdaExpression = Expression.Lambda&lt;Func&lt;SomeClass, Decimal&gt;&gt;(dtoPropertySelector, new ParameterExpression[] { dtoTypeParameter });

    return lamdaExpression.Compile();
}

Decimal GetTotal(String fieldName, IEnumerable&lt;SomeClass&gt; lists)
{
    // solution - generate the func in run-time
    var runTimeSelector = GetMyFunc(fieldName);
    var totalByLinq = lists.Sum(runTimeSelector);
    return totalByLinq;
}
</pre></p>
<p>It&#8217;s surely world of possibilities with this expression trees ;)</p>
<p>Full source code below:<br />
<pre class="brush: csharp;">
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var lists = new List&lt;SomeClass&gt; {
            new SomeClass { DailyFunctionalAmount = 10, MonthToDateFunctionalAmount = 100},
            new SomeClass { DailyFunctionalAmount = 10, MonthToDateFunctionalAmount = 100},
        };

        var lookups = new Dictionary&lt;String, Decimal&gt;(); // stored with the property name as key in the dictionary and the sum as value
        lookups.Add(&quot;DailyFunctionalAmount&quot;, 20);
        lookups.Add(&quot;MonthToDateFunctionalAmount&quot;, 200);

        var dailyFunctionalFieldName = GetFieldName(&quot;Daily&quot;, &quot;Functional&quot;);
        var monthToDateFunctionalFieldName = GetFieldName(&quot;MonthToDate&quot;, &quot;Functional&quot;);

        // old way
        Assert.AreEqual(20, GetTotal(dailyFunctionalFieldName, lookups));
        Assert.AreEqual(200, GetTotal(monthToDateFunctionalFieldName, lookups));

        // new way 
        Assert.AreEqual(20, GetTotal(dailyFunctionalFieldName, lists));
        Assert.AreEqual(200, GetTotal(monthToDateFunctionalFieldName, lists));
    }

    Decimal GetTotal(String fieldName, IDictionary&lt;String, Decimal&gt; lookups)
    {
        // used to be as simple as getting the pre-calculated sum via dictionary (populated somewhere else by control)
        var totalByLookup = lookups[fieldName];
        return totalByLookup;
    }

    Decimal GetTotal(String fieldName, IEnumerable&lt;SomeClass&gt; lists)
    {
        // now it needs to be manually calculated from the list

        //var totalByLinq = lists.Sum(r =&gt; r.DailyFunctionalAmount); // but this is compiled/pre-determined code where we actually need the selector in run-time

        // solution - generate the func in run-time
        var runTimeSelector = GetMyFunc(fieldName);
        var totalByLinq = lists.Sum(runTimeSelector);
        return totalByLinq;
    }

    String GetFieldName(String periodic, String currency)
    {
        // the field name is generated by some convention [Daily/MonthToDate] + [Functional/Transaction] + &quot;Amount&quot;
        return periodic + currency + &quot;Amount&quot;;
    }

    // returns -&gt; dtoType =&gt; dtoType.propertyName
    Func&lt;SomeClass, Decimal&gt; GetMyFunc(string propertyName)
    {
        var dtoTypeParameter = Expression.Parameter(typeof(SomeClass), &quot;dtoType&quot;);
        var dtoPropertySelector = Expression.Property(dtoTypeParameter, propertyName);
        var lamdaExpression = Expression.Lambda&lt;Func&lt;SomeClass, Decimal&gt;&gt;(dtoPropertySelector, new ParameterExpression[] { dtoTypeParameter });

        return lamdaExpression.Compile();
    }
}

class SomeClass
{
    public Decimal DailyFunctionalAmount { get; set; }
    public Decimal MonthToDateFunctionalAmount { get; set; }
    ///..... have much more here
}
</pre></p>
<br /> Tagged: <a href='http://bembengarifin.wordpress.com/tag/c/'>C#</a>, <a href='http://bembengarifin.wordpress.com/tag/expression-trees/'>Expression Trees</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bembengarifin.wordpress.com/361/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bembengarifin.wordpress.com/361/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bembengarifin.wordpress.com/361/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bembengarifin.wordpress.com/361/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bembengarifin.wordpress.com/361/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bembengarifin.wordpress.com/361/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bembengarifin.wordpress.com/361/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bembengarifin.wordpress.com/361/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bembengarifin.wordpress.com/361/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bembengarifin.wordpress.com/361/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bembengarifin.wordpress.com/361/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bembengarifin.wordpress.com/361/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bembengarifin.wordpress.com/361/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bembengarifin.wordpress.com/361/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=361&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://bembengarifin.wordpress.com/2011/11/08/generate-func-by-using-expression-trees/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/16667ddc52caff2b1718e96fdcfc6e69?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bembengarifin</media:title>
		</media:content>
	</item>
		<item>
		<title>Blending with Sample Data feature (Blend 4)</title>
		<link>http://bembengarifin.wordpress.com/2011/07/15/blending-with-sample-data-feature-blend-4/</link>
		<comments>http://bembengarifin.wordpress.com/2011/07/15/blending-with-sample-data-feature-blend-4/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 11:54:00 +0000</pubDate>
		<dc:creator>Bembeng Arifin</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Blend]]></category>

		<guid isPermaLink="false">http://bembengarifin.wordpress.com/?p=340</guid>
		<description><![CDATA[Had a chance to play more with Blend 4 this week, have been eyeing on the Sample Data feature for a while but only had a chance to use it in practice now. So imagine if you have defined the backing view model below You can then open the view, on the top right panel, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=340&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Had a chance to play more with Blend 4 this week, have been eyeing on the Sample Data feature for a while but only had a chance to use it in practice now.</p>
<p>So imagine if you have defined the backing view model below</p>
<p><pre class="brush: csharp;">
public class MainViewModel
{
	public MainViewModel()
	{
		// Insert code required on object creation below this point.
	}
	public IList&lt;Person&gt; Persons { get; set; }
}

public abstract class Person
{
	public String Name { get; set; }
	public Int32 Age { get; set; }
	public String Initials { get{ return &quot;some initials&quot;; } }
}

public class Male : Person
{
}

public class Female : Person
{
}
</pre></p>
<p>You can then open the view, on the top right panel, click on the Create Sample Data from Class option below</p>
<p><a href="http://bembengarifin.files.wordpress.com/2011/07/blend-create-sample-data-from-class1.jpg"><img class="align size-full wp-image-345" title="Blend - Create Sample Data from Class" src="http://bembengarifin.files.wordpress.com/2011/07/blend-create-sample-data-from-class1.jpg?w=600" alt=""   /></a></p>
<p>Choose the view model to generate the sample data, click Ok</p>
<p><a href="http://bembengarifin.files.wordpress.com/2011/07/blend-choose-view-model.jpg"><img class="align size-full wp-image-346" title="Blend - Choose View Model" src="http://bembengarifin.files.wordpress.com/2011/07/blend-choose-view-model.jpg?w=600" alt=""   /></a></p>
<p>Bam! the sample data file has been generated nicely below, and notice one thing, the read only Initials property can be &#8220;set&#8221; as well there :)</p>
<p><a href="http://bembengarifin.files.wordpress.com/2011/07/blend-generated-sample-data.jpg"><img class="align size-full wp-image-347" title="Blend - Generated sample data" src="http://bembengarifin.files.wordpress.com/2011/07/blend-generated-sample-data.jpg?w=600" alt="" /></a><br />
Before moving on to the next step, be sure to replace Person Type on the rows into either Male or Female.</p>
<p>Now, time to get into the view with the d:DataContext binding and data templates by Data Type for each Male and Female.<br />
<a href="http://bembengarifin.files.wordpress.com/2011/07/blend-datatemplate-not-working.jpg"><img class="align size-full wp-image-348" title="Blend - DataTemplate not working" src="http://bembengarifin.files.wordpress.com/2011/07/blend-datatemplate-not-working.jpg?w=600&#038;h=508" alt="" width="600" height="508" /></a></p>
<p>hhhmm&#8230; a little bit disappointing, isn&#8217;t it? all are seem to be in place, but why it&#8217;s displaying these weirds _.di12.NameSpace.Class rather than our expected data template result?<br />
Now back to the xaml, add d:IsDesignTimeCreatable=&#8221;False&#8221; attribute on both data template elements, save, close and reopen the xaml again.</p>
<p>And there&#8217;s the <em>shiny</em> UI with some sample data in it :)</p>
<p><a href="http://bembengarifin.files.wordpress.com/2011/07/blend-isdesigntimecreatable.jpg"><img class="align size-full wp-image-351" title="Blend - IsDesignTimeCreatable" src="http://bembengarifin.files.wordpress.com/2011/07/blend-isdesigntimecreatable.jpg?w=600&#038;h=588" alt="" width="600" height="588" /></a></p>
<p>Notice that Blend sometimes doesn&#8217;t refresh the design view as soon as we make some changes on the data template (it works fine on non data template changes).<br />
I only found that the effective way is to just close and reopen to see the changes effect, so if you&#8217;re editing something on the data template and it&#8217;s not reflecting, try to close and reopen it first :)</p>
<p>I found this sample data feature is very useful, how bout you?</p>
<p>Have also shared <a href="https://skydrive.live.com/?cid=41c0c9ecd9d35c8f&amp;sc=documents&amp;id=41C0C9ECD9D35C8F%21181#" target="_blank">the sample project for grabs here</a>.</p>
<p>Hope this helps :)</p>
<br /> Tagged: <a href='http://bembengarifin.wordpress.com/tag/blend/'>Blend</a>, <a href='http://bembengarifin.wordpress.com/tag/mvvm/'>MVVM</a>, <a href='http://bembengarifin.wordpress.com/tag/visual-studio/'>Visual Studio</a>, <a href='http://bembengarifin.wordpress.com/tag/wpf/'>WPF</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bembengarifin.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bembengarifin.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bembengarifin.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bembengarifin.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bembengarifin.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bembengarifin.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bembengarifin.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bembengarifin.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bembengarifin.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bembengarifin.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bembengarifin.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bembengarifin.wordpress.com/340/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bembengarifin.wordpress.com/340/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bembengarifin.wordpress.com/340/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=340&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://bembengarifin.wordpress.com/2011/07/15/blending-with-sample-data-feature-blend-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/16667ddc52caff2b1718e96fdcfc6e69?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bembengarifin</media:title>
		</media:content>

		<media:content url="http://bembengarifin.files.wordpress.com/2011/07/blend-create-sample-data-from-class1.jpg" medium="image">
			<media:title type="html">Blend - Create Sample Data from Class</media:title>
		</media:content>

		<media:content url="http://bembengarifin.files.wordpress.com/2011/07/blend-choose-view-model.jpg" medium="image">
			<media:title type="html">Blend - Choose View Model</media:title>
		</media:content>

		<media:content url="http://bembengarifin.files.wordpress.com/2011/07/blend-generated-sample-data.jpg" medium="image">
			<media:title type="html">Blend - Generated sample data</media:title>
		</media:content>

		<media:content url="http://bembengarifin.files.wordpress.com/2011/07/blend-datatemplate-not-working.jpg" medium="image">
			<media:title type="html">Blend - DataTemplate not working</media:title>
		</media:content>

		<media:content url="http://bembengarifin.files.wordpress.com/2011/07/blend-isdesigntimecreatable.jpg" medium="image">
			<media:title type="html">Blend - IsDesignTimeCreatable</media:title>
		</media:content>
	</item>
		<item>
		<title>Fallen into the pit of overconfidence</title>
		<link>http://bembengarifin.wordpress.com/2011/06/02/fallen-into-the-pit-of-overconfidence/</link>
		<comments>http://bembengarifin.wordpress.com/2011/06/02/fallen-into-the-pit-of-overconfidence/#comments</comments>
		<pubDate>Thu, 02 Jun 2011 16:46:10 +0000</pubDate>
		<dc:creator>Bembeng Arifin</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://bembengarifin.wordpress.com/?p=318</guid>
		<description><![CDATA[If someone had asked me yesterday whether I&#8217;m a professional, mature, seasoned developer. I would certainly replied &#8220;Indeed, I am!&#8221;. Well, fortunately, no one did, or else I can&#8217;t imagine meeting him/her again today after the pathetic thing below. You see, I was working on a defect/bug yesterday, it was a pretty simple bug that I [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=318&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>If someone had asked me yesterday whether I&#8217;m a professional, mature, seasoned developer. I would certainly replied &#8220;Indeed, I am!&#8221;. Well, fortunately, no one did, or else I can&#8217;t imagine meeting him/her again today after the pathetic thing below.</p>
<p>You see, I was working on a defect/bug yesterday, it was a pretty simple bug that I was happily to fix as it looks like a less than an hour job, so I did the fix below, got the test evidences and marked that defect as fixed, ready for promotion to the test environment.</p>
<p><pre class="brush: csharp;">
private Boolean _someFlag;
private String _someOption;

private void Execute()
{
    //... some codes here

    // the following block of codes is the fix to resolve the defect/bug
    if (_someOption.Contains(&quot;something&quot;))
    {
        _someFlag = true;
    }
    else
    {
        _someFlag = false;
    }

    //... some codes here
}
</pre></p>
<p>To my horror this morning, there&#8217;s a new defect being raised, complaining that there&#8217;s an error pop-up whenever the user tried to click on the execute button.</p>
<p><a href="http://bembengarifin.files.wordpress.com/2011/06/nullreferenceexception.jpg"><img class="size-full wp-image-319" title="NullReferenceException" src="http://bembengarifin.files.wordpress.com/2011/06/nullreferenceexception.jpg?w=600" alt=""   /></a></p>
<p>And quickly I realized that the error was coming from the modified code above. And to make things worst, the code above is in the base class of let say 10 UI forms and 3 of them are now not working/usable at all due to this new bug.</p>
<p>Now fixing this new bug is another simple task to do, but the thing that stayed on my mind till now is that when I wrote that fix yesterday, it actually came to my mind that I should be putting some unit tests on them, this new bug will definitely get captured if I were to write the unit tests (basic positive, negative, null tests). But nah, my overconfidence took over that this is a simple fix, nothing&#8217;s going to ever happen with this fix, everything will be running happily tomorrow, I should check this in ASAP and hurrah! one defect down. </p>
<p>So what are the consequences with that?</p>
<ol>
<li>Testing activities were blocked on for 3 of 10 UIs, where actually without the code fix, all were actually working fine, it&#8217;s just a minor dodgy state that was incorrect</li>
<li>One more day was wasted to get the new fix promoted so the testing can be continued</li>
<li>For having end users/testers to actually see this error message, it&#8217;s embarrassing the development team</li>
<li>And in the end, this kind of error is truly embarrassing for a .Net programmer, with these years of experiences for sure :|</li>
</ol>
<div>The following is an excerpt taken from<a href="http://www.objectmentor.com/omTeam/martin_r.html" target="_blank"> Uncle Bob Martin</a>&#8216;s <a href="http://www.amazon.com/Clean-Coder-Conduct-Professional-Programmers/dp/0137081073/ref=bxgy_cc_b_img_b" target="_blank">The Clean Coder</a> book.</div>
<p> (hope you don&#8217;t mind, Uncle Bob, I&#8217;ll make sure that I write the book review when I&#8217;m done reading your book :))</p>
<blockquote><p>As you mature in your profession, your error rate should rapidly decrease towards the asymptote of zero. It won’t ever get to zero, but it is your responsibility to get as close as possible to it.</p></blockquote>
<p>Hit the nail on the head of what I was expected to do. So moral of the story, be humble, don&#8217;t ignore your inner voice, and believe in unit testing/TDD. </p>
<p>PS: Tony, if you actually read this, just know that today in my head, i kept imagining you&#8217;re telling me &#8220;See, I told you, Bembeng&#8221; :p</p>
<br /> Tagged: <a href='http://bembengarifin.wordpress.com/tag/unit-test/'>unit test</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bembengarifin.wordpress.com/318/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bembengarifin.wordpress.com/318/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bembengarifin.wordpress.com/318/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bembengarifin.wordpress.com/318/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bembengarifin.wordpress.com/318/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bembengarifin.wordpress.com/318/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bembengarifin.wordpress.com/318/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bembengarifin.wordpress.com/318/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bembengarifin.wordpress.com/318/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bembengarifin.wordpress.com/318/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bembengarifin.wordpress.com/318/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bembengarifin.wordpress.com/318/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bembengarifin.wordpress.com/318/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bembengarifin.wordpress.com/318/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=318&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://bembengarifin.wordpress.com/2011/06/02/fallen-into-the-pit-of-overconfidence/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/16667ddc52caff2b1718e96fdcfc6e69?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bembengarifin</media:title>
		</media:content>

		<media:content url="http://bembengarifin.files.wordpress.com/2011/06/nullreferenceexception.jpg" medium="image">
			<media:title type="html">NullReferenceException</media:title>
		</media:content>
	</item>
		<item>
		<title>New CLR Profiler for .NET Framework 4</title>
		<link>http://bembengarifin.wordpress.com/2011/05/25/new-clr-profiler-for-net-framework-4/</link>
		<comments>http://bembengarifin.wordpress.com/2011/05/25/new-clr-profiler-for-net-framework-4/#comments</comments>
		<pubDate>Wed, 25 May 2011 08:35:33 +0000</pubDate>
		<dc:creator>Bembeng Arifin</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Debugging]]></category>

		<guid isPermaLink="false">http://bembengarifin.wordpress.com/?p=306</guid>
		<description><![CDATA[We just found a memory leak (again) in our latest code base that we&#8217;re going to release to production next month, seems that we&#8217;re having this issue for every release :p i think it&#8217;s unavoidable considering the amount of changes that we&#8217;re making on the app for each release ;) Now, when I tried to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=306&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>We just found a memory leak (again) in our latest code base that we&#8217;re going to release to production next month, seems that we&#8217;re having this issue for every release :p i think it&#8217;s unavoidable considering the amount of changes that we&#8217;re making on the app for each release ;)</p>
<p>Now, when I tried to do the <a href="http://bembengarifin.wordpress.com/2011/02/28/how-to-confirm-memory-leak-with-perfmon-and-clr-profiler/" target="_blank">regular steps</a> to investigate the root cause, the CLR Profiler was not responding when I clicked the Show Heap now button and eventually display the pop-up below.</p>
<p><a href="http://bembengarifin.files.wordpress.com/2011/05/clrprofiler2.jpg"><img class="size-full wp-image-308" title="CLRProfiler2" src="http://bembengarifin.files.wordpress.com/2011/05/clrprofiler2.jpg?w=600" alt=""   /></a></p>
<p>Then realised that since we have just upgraded the application to use .Net 4.0, so there&#8217;s a chance that there&#8217;s a new CLR Profiler on the block for .Net 4.0, and turned out there is actually a <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=be2d842b-fdce-4600-8d32-a3cf74fda5e1" target="_blank">new one available in MSDN</a>. And it&#8217;s not surprising, considering that .Net 4.0 comes with a new CLR as well (click on the image below to go to the msdn website for more info)</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb822049.aspx"><img class="size-full wp-image-308" src="http://i.msdn.microsoft.com/dynimg/IC446978.png" alt="" /></a></p>
<p>After downloaded the new CLR Profiler 4, it looks like below, notice the new Attach Process and Detach Process buttons, those will be very useful as we always need to start the application in the previous version, sweet! :)</p>
<p><a href="http://bembengarifin.files.wordpress.com/2011/05/clrprofiler4.jpg"><img class="size-full wp-image-309" title="CLRProfiler4" src="http://bembengarifin.files.wordpress.com/2011/05/clrprofiler4.jpg?w=600" alt=""   /></a></p>
<p>Now, it&#8217;s time to duck into the the heap :)</p>
<br /> Tagged: <a href='http://bembengarifin.wordpress.com/tag/c/'>C#</a>, <a href='http://bembengarifin.wordpress.com/tag/debugging/'>Debugging</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bembengarifin.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bembengarifin.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bembengarifin.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bembengarifin.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bembengarifin.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bembengarifin.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bembengarifin.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bembengarifin.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bembengarifin.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bembengarifin.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bembengarifin.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bembengarifin.wordpress.com/306/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bembengarifin.wordpress.com/306/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bembengarifin.wordpress.com/306/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=306&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://bembengarifin.wordpress.com/2011/05/25/new-clr-profiler-for-net-framework-4/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/16667ddc52caff2b1718e96fdcfc6e69?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bembengarifin</media:title>
		</media:content>

		<media:content url="http://bembengarifin.files.wordpress.com/2011/05/clrprofiler2.jpg" medium="image">
			<media:title type="html">CLRProfiler2</media:title>
		</media:content>

		<media:content url="http://i.msdn.microsoft.com/dynimg/IC446978.png" medium="image" />

		<media:content url="http://bembengarifin.files.wordpress.com/2011/05/clrprofiler4.jpg" medium="image">
			<media:title type="html">CLRProfiler4</media:title>
		</media:content>
	</item>
		<item>
		<title>Controlling the concurrency level using MaxDegreeOfParallelism in Parallel</title>
		<link>http://bembengarifin.wordpress.com/2011/04/15/controlling-the-concurrency-level-using-maxdegreeofparallelism-in-parallel/</link>
		<comments>http://bembengarifin.wordpress.com/2011/04/15/controlling-the-concurrency-level-using-maxdegreeofparallelism-in-parallel/#comments</comments>
		<pubDate>Fri, 15 Apr 2011 14:06:22 +0000</pubDate>
		<dc:creator>Bembeng Arifin</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[TPL]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://bembengarifin.wordpress.com/?p=293</guid>
		<description><![CDATA[This is another nice available in the box feature when using the Parallel class, is the ability to basically limit the concurrency for the actions that we want to execute in parallel. Why would we ever want to do this? wouldn&#8217;t it be best if we parallel some activities as many as possible? For certain cases, we [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=293&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>This is another nice available in the box feature when using the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.aspx" target="_blank">Parallel</a> class, is the ability to basically limit the concurrency for the actions that we want to execute in parallel.</p>
<p>Why would we ever want to do this? wouldn&#8217;t it be best if we parallel some activities as many as possible?</p>
<p>For certain cases, we might want to be careful for not creating too many sudden requests at the same time, a good example will be if we&#8217;re triggering a long running process in our application server, you wouldn&#8217;t want to spawn too many requests at the same time to the server, as the server may not be able to handle so many requests at the same time and not surprisingly go down due to overload. This can be categorized as <a href="http://en.wikipedia.org/wiki/Denial-of-service_attack" target="_blank">DOS</a> attack, your back end guys will hate you for this, trust me :p</p>
<p>To set the concurrency level of the actions that you&#8217;re going to invoke with the Parallel class is pretty simple.</p>
<p><pre class="brush: csharp;">
Parallel.Invoke(new ParallelOptions() { MaxDegreeOfParallelism = concurrencyLevel }, actions);
</pre></p>
<p>Find more about the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.paralleloptions.maxdegreeofparallelism.aspx" target="_blank">MaxDegreeOfParallelism property in msdn</a>.<br />
We don&#8217;t have this such of property in the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskcreationoptions.aspx" target="_blank">TaskCreationOptions</a> that we can simply pass for <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx" target="_blank">Task</a>, but there&#8217;s a <a href="http://msdn.microsoft.com/en-us/library/ee789351.aspx" target="_blank">LimitedConcurrencyLevelTaskScheduler</a> nicely available which we can achieve the same result below where i basically spawn 10 processes with 2 max concurrency level.</p>
<p><code><br />
15-Apr-2011 21:04:33.948 - Thead#13 - Creating 10 process definitions<br />
15-Apr-2011 21:04:33.948 - Thead#13 - Start queueing and invoking all 10 processes<br />
15-Apr-2011 21:04:33.948 - Thead#13 - Doing something here<br />
15-Apr-2011 21:04:33.948 - Thead#14 - Doing something here<br />
15-Apr-2011 21:04:34.964 - Thead#13 - Doing something here<br />
15-Apr-2011 21:04:34.964 - Thead#14 - Doing something here<br />
15-Apr-2011 21:04:35.964 - Thead#13 - Doing something here<br />
15-Apr-2011 21:04:35.964 - Thead#14 - Doing something here<br />
15-Apr-2011 21:04:36.964 - Thead#13 - Doing something here<br />
15-Apr-2011 21:04:36.964 - Thead#14 - Doing something here<br />
15-Apr-2011 21:04:37.964 - Thead#13 - Doing something here<br />
15-Apr-2011 21:04:37.964 - Thead#14 - Doing something here<br />
15-Apr-2011 21:04:38.964 - Thead#13 - All processes have been completed<br />
</code></p>
<p><pre class="brush: csharp;">
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ParallelTests
{
    [TestClass]
    public class TaskSchedulerConcurrencyTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            var p = new ProcessorUsingParallel();
            p.DoProcess(processToCreate: 10, concurrencyLevel: 2);
        }
    }

    public class ProcessorUsingParallel
    {
        public void DoProcess(int processToCreate, int concurrencyLevel)
        {
            SetTurboMode();

            Debug(&quot;Creating {0} process definitions&quot;, processToCreate.ToString());

            var actions = new Action[processToCreate];
            for (int i = 0; i &lt; processToCreate; i++)
            {
                actions[i] = () =&gt; DoSomething(1000);
            }

            Debug(&quot;Start queueing and invoking all {0} processes&quot;, processToCreate.ToString());
            var options = new ParallelOptions();
            options.MaxDegreeOfParallelism = concurrencyLevel;
            //options.TaskScheduler = new LimitedConcurrencyLevelTaskScheduler(concurrencyLevel); -- we can achieve the same result with this
            Parallel.Invoke(options, actions);

            Debug(&quot;All processes have been completed&quot;);
        }

        private void DoSomething(int Sleep)
        {
            Debug(&quot;Doing something here&quot;);
            Thread.Sleep(Sleep);
        }

        /// &lt;summary&gt;
        /// oh i just wish the framework would have this in place like Console.WriteLine
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;format&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;args&quot;&gt;&lt;/param&gt;
        private static void Debug(string format, params object[] args)
        {
            System.Diagnostics.Debug.WriteLine(
                string.Format(&quot;{0} - Thead#{1} - {2}&quot;,
                    DateTime.Now.ToString(&quot;dd-MMM-yyyy HH:mm:ss.fff&quot;),
                    Thread.CurrentThread.ManagedThreadId.ToString(),
                    string.Format(format, args)));
        }
        /// &lt;summary&gt;
        /// This is not intended for production purpose
        /// &lt;/summary&gt;
        private static void SetTurboMode()
        {
            int t, io;
            ThreadPool.GetMaxThreads(out t, out io);
            Debug(&quot;Default Max {0}, I/O: {1}&quot;, t, io);

            var success = ThreadPool.SetMinThreads(t, io);
            Debug(&quot;Successfully set Min {0}, I/O: {1}&quot;, t, io);
        }
    }
}

</pre></p>
<br /> Tagged: <a href='http://bembengarifin.wordpress.com/tag/c/'>C#</a>, <a href='http://bembengarifin.wordpress.com/tag/multithreading/'>Multithreading</a>, <a href='http://bembengarifin.wordpress.com/tag/performance/'>performance</a>, <a href='http://bembengarifin.wordpress.com/tag/tpl/'>TPL</a>, <a href='http://bembengarifin.wordpress.com/tag/unit-test/'>unit test</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bembengarifin.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bembengarifin.wordpress.com/293/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bembengarifin.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bembengarifin.wordpress.com/293/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bembengarifin.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bembengarifin.wordpress.com/293/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bembengarifin.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bembengarifin.wordpress.com/293/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bembengarifin.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bembengarifin.wordpress.com/293/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bembengarifin.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bembengarifin.wordpress.com/293/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bembengarifin.wordpress.com/293/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bembengarifin.wordpress.com/293/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=293&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://bembengarifin.wordpress.com/2011/04/15/controlling-the-concurrency-level-using-maxdegreeofparallelism-in-parallel/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/16667ddc52caff2b1718e96fdcfc6e69?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bembengarifin</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Parallel in .Net 4.0 without worrying WaitHandle.WaitAll 64 handles limitation</title>
		<link>http://bembengarifin.wordpress.com/2011/04/11/using-parallel-in-net-4-0-without-worrying-waithandle-waitall-64-handles-limitation/</link>
		<comments>http://bembengarifin.wordpress.com/2011/04/11/using-parallel-in-net-4-0-without-worrying-waithandle-waitall-64-handles-limitation/#comments</comments>
		<pubDate>Mon, 11 Apr 2011 16:55:20 +0000</pubDate>
		<dc:creator>Bembeng Arifin</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[TPL]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://bembengarifin.wordpress.com/?p=287</guid>
		<description><![CDATA[As my previous post was providing an example of using the Task class from the TPL library to overcome the 64 waithandles limitation on WaitHandle.WaitAll, here&#8217;s the other alternative of code which leverage the Parallel class from the same library. Here&#8217;s the download link for the whole test project. However, notice one thing below that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=287&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As my previous post was providing an example of using the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.aspx" target="_blank">Task</a> class from the <a href="http://msdn.microsoft.com/en-us/library/dd460717.aspx" target="_blank">TPL</a> library to overcome the 64 waithandles limitation on WaitHandle.WaitAll, here&#8217;s the other alternative of code which leverage the <a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.parallel.aspx" target="_blank">Parallel</a> class from the same library. Here&#8217;s the <a href="http://cid-41c0c9ecd9d35c8f.office.live.com/self.aspx/Public/ParallelismTests.zip" target="_blank">download link</a> for the whole test project.</p>
<p>However, notice one thing below that I&#8217;m using <a href="http://msdn.microsoft.com/en-us/library/dd381779.aspx" target="_blank">ConcurrentBag&lt;T&gt;</a> type which is a thread-safe bag implementation, optimized for scenarios where the same thread will be both producing and consuming data stored in the bag (taken from the msdn page).</p>
<p>An interesting fact with this, it takes around 74 secs to complete where if we&#8217;re not concern about return values (remove the usage of the ConcurrentBag&lt;T&gt;), it will only take around 28 seconds where using Task (with or without return values), it will only take 22 secs. I guess we can probably use a &#8220;state object&#8221; to pass into the invocation to hold the values for each process to avoid the locking costs, but since Task is already doing this well, it will need a justification why we need to do that manually ourselves with Parallel.Invoke solution. Moral of the story: always get the facts first by each alternative for your solution then decision will be easy and justifiable.</p>
<p><pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;

namespace ParallelismTests
{
    [TestClass]
    public class ParallelTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            var p = new ProcessorUsingParallel();
            var counts = p.DoProcess(hiLevelParallelism: 1000, loLevelParallelism: 1000);

            Assert.AreEqual(1000 * 1000, counts);
        }
    }

    public class ProcessorUsingParallel
    {
        public int DoProcess(int hiLevelParallelism, int loLevelParallelism)
        {
            Utility.SetTurboMode();

            Utility.Debug(&quot;Start queueing {0} high level processes&quot;, hiLevelParallelism.ToString());

            var counts = new ConcurrentBag&lt;int&gt;();
            var r = new Random();

            var actions = new Action[hiLevelParallelism];
            for (int i = 0; i &lt; hiLevelParallelism; i++)
            {
                actions[i] = () =&gt; counts.Add(DoHighLevelProcess(r, loLevelParallelism));
            }

            Utility.Debug(&quot;Invoking all {0} high level tasks&quot;, hiLevelParallelism.ToString());
            Parallel.Invoke(actions);

            Utility.Debug(&quot;All processes have been completed&quot;);
            return counts.Sum(t =&gt; t);
        }

        private int DoHighLevelProcess(Random r, int loLevelParallelism)
        {
            var counts = new ConcurrentBag&lt;int&gt;();
            var actions = new Action[loLevelParallelism];
            for (int i = 0; i &lt; loLevelParallelism; i++)
            {
                actions[i] = () =&gt; counts.Add(DoLowLevelProcess(r.Next(1, 10)));
            }
            Parallel.Invoke(actions);

            Utility.Debug(&quot;DoHighLevelProcess - Completed with {0} LowLeveProcesses&quot;, loLevelParallelism);
            return counts.Sum(t =&gt; t);
        }
        private int DoLowLevelProcess(int Sleep)
        {
            Thread.Sleep(Sleep);
            return 1;
        }
    }
}
</pre></p>
<br /> Tagged: <a href='http://bembengarifin.wordpress.com/tag/c/'>C#</a>, <a href='http://bembengarifin.wordpress.com/tag/multithreading/'>Multithreading</a>, <a href='http://bembengarifin.wordpress.com/tag/performance/'>performance</a>, <a href='http://bembengarifin.wordpress.com/tag/tpl/'>TPL</a>, <a href='http://bembengarifin.wordpress.com/tag/unit-test/'>unit test</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bembengarifin.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bembengarifin.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bembengarifin.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bembengarifin.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bembengarifin.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bembengarifin.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bembengarifin.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bembengarifin.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bembengarifin.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bembengarifin.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bembengarifin.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bembengarifin.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bembengarifin.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bembengarifin.wordpress.com/287/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=287&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://bembengarifin.wordpress.com/2011/04/11/using-parallel-in-net-4-0-without-worrying-waithandle-waitall-64-handles-limitation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/16667ddc52caff2b1718e96fdcfc6e69?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bembengarifin</media:title>
		</media:content>
	</item>
		<item>
		<title>Using Task in .Net 4.0 without worrying WaitHandle.WaitAll 64 handles limitation</title>
		<link>http://bembengarifin.wordpress.com/2011/04/07/using-task-in-net-4-0-without-worrying-waithandle-waitall-64-handles-limitation/</link>
		<comments>http://bembengarifin.wordpress.com/2011/04/07/using-task-in-net-4-0-without-worrying-waithandle-waitall-64-handles-limitation/#comments</comments>
		<pubDate>Thu, 07 Apr 2011 16:21:31 +0000</pubDate>
		<dc:creator>Bembeng Arifin</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[TPL]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://bembengarifin.wordpress.com/?p=272</guid>
		<description><![CDATA[In my previous post, I was looking into having 2 level of concurrent processes, creating concurrent processes which will spawn another concurrent processes each. Now by using WaitHandle.WaitAll, we can see there&#8217;s a limit of 64 waithandles for waiting, so with the new Task Parallel Library in .Net 4.0, we don&#8217;t have to worry about that [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=272&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In my previous <a href="http://bembengarifin.wordpress.com/2011/04/04/demystifying-64-handles-limit-in-waithandle-waitall/" target="_blank">post</a>, I was looking into having 2 level of concurrent processes, creating concurrent processes which will spawn another concurrent processes each.</p>
<p>Now by using <a href="http://msdn.microsoft.com/en-us/library/z6w25xa6.aspx" target="_blank">WaitHandle.WaitAll</a>, we can see there&#8217;s a limit of 64 waithandles for waiting, so with the new <a href="http://msdn.microsoft.com/en-us/library/dd460717.aspx" target="_blank">Task Parallel Library</a> in .Net 4.0, we don&#8217;t have to worry about that kind of limitation anymore.</p>
<p>Using the code in the previous post, I then used the Task class to perform the concurrent processes. Notice the code below, I&#8217;m actually create 1.000 high level processes which will create 1.000 low level processes each, so in total 1.000.000 processes. And another very nice thing here is that we can actually return a value from each task very easily compared to the previous solution using Threadpool.</p>
<p>One more interesting here is that, noticed the line#40 &amp; #54: <code>Task.WaitAll(tasks.ToArray());</code>, with that line in place, it would only take 20+ seconds to complete where without it (remove/comment those lines), it would then take 11 minutes. That a pretty huge difference ;)</p>
<p>Reason: I think it makes sense, because without that line, we will be waiting for the task completion sequentially in the SUM operation when Task.Result was being called, where the completion of 1 task with the next/previous task in the collection might be different, where Task.WaitAll will basically get all the signals by each task as when it completed, so when the SUM operation is being called, all the results are already available without any need to wait anymore :)</p>
<p><pre class="brush: csharp;">
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using System.Threading;

namespace ParallelismTests
{
    [TestClass]
    public class TaskTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            var p = new ProcessorUsingTask();
            var counts = p.DoProcess(hiLevelParallelism: 1000, loLevelParallelism: 1000);

            Assert.AreEqual(1000*1000, counts);
        }
    }

    public class ProcessorUsingTask
    {
        public int DoProcess(int hiLevelParallelism, int loLevelParallelism)
        {
            SetTurboMode();

            Debug(&quot;Start queueing {0} high level processes&quot;, hiLevelParallelism.ToString());

            var tasks = new List&lt;Task&lt;int&gt;&gt;();
            var r = new Random();
            for (int i = 0; i &lt; hiLevelParallelism; i++)
            {
                var task = Task.Factory.StartNew&lt;int&gt;(() =&gt; DoHighLevelProcess(r, loLevelParallelism));
                tasks.Add(task);
            }

            Debug(&quot;Waiting for all {0} high level tasks to complete&quot;, hiLevelParallelism.ToString());
            Task.WaitAll(tasks.ToArray()); // try comment this line out and see the performance impact :)

            Debug(&quot;All processes have been completed&quot;);
            return tasks.Sum(t =&gt; t.Result);
        }

        private int DoHighLevelProcess(Random r, int loLevelParallelism)
        {
            var tasks = new List&lt;Task&lt;int&gt;&gt;();
            for (int i = 0; i &lt; loLevelParallelism; i++)
            {
                var task = Task.Factory.StartNew&lt;int&gt;(() =&gt; DoLowLevelProcess(r.Next(1, 10)));
                tasks.Add(task);
            }
            Task.WaitAll(tasks.ToArray()); // try comment this line out and see the performance impact :)
            
            Debug(&quot;DoHighLevelProcess - Completed with {0} LowLeveProcesses&quot;, loLevelParallelism);
            return tasks.Sum(t =&gt; t.Result);
        }
        private int DoLowLevelProcess(int Sleep)
        {
            Thread.Sleep(Sleep);
            //Debug(&quot;DoLowLevelProcess - Completed after {0} ms&quot;, Sleep.ToString());
            return 1;
        }

        /// &lt;summary&gt;
        /// oh i just wish the framework would have this in place like Console.WriteLine
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;format&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;args&quot;&gt;&lt;/param&gt;
        private static void Debug(string format, params object[] args)
        {
            System.Diagnostics.Debug.WriteLine(
                string.Format(&quot;{0} - Thead#{1} - {2}&quot;,
                    DateTime.Now.ToString(&quot;dd-MMM-yyyy HH:mm:ss.fff&quot;),
                    Thread.CurrentThread.ManagedThreadId.ToString(),
                    string.Format(format, args)));
        }
        /// &lt;summary&gt;
        /// This is not intended for production purpose
        /// &lt;/summary&gt;
        private static void SetTurboMode()
        {
            int t, io;
            ThreadPool.GetMaxThreads(out t, out io);
            Debug(&quot;Default Max {0}, I/O: {1}&quot;, t, io);

            var success = ThreadPool.SetMinThreads(t, io);
            Debug(&quot;Successfully set Min {0}, I/O: {1}&quot;, t, io);
        }
    }
}
</pre></p>
<br /> Tagged: <a href='http://bembengarifin.wordpress.com/tag/c/'>C#</a>, <a href='http://bembengarifin.wordpress.com/tag/multithreading/'>Multithreading</a>, <a href='http://bembengarifin.wordpress.com/tag/performance/'>performance</a>, <a href='http://bembengarifin.wordpress.com/tag/tpl/'>TPL</a>, <a href='http://bembengarifin.wordpress.com/tag/unit-test/'>unit test</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bembengarifin.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bembengarifin.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bembengarifin.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bembengarifin.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bembengarifin.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bembengarifin.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bembengarifin.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bembengarifin.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bembengarifin.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bembengarifin.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bembengarifin.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bembengarifin.wordpress.com/272/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bembengarifin.wordpress.com/272/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bembengarifin.wordpress.com/272/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=272&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://bembengarifin.wordpress.com/2011/04/07/using-task-in-net-4-0-without-worrying-waithandle-waitall-64-handles-limitation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/16667ddc52caff2b1718e96fdcfc6e69?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bembengarifin</media:title>
		</media:content>
	</item>
		<item>
		<title>Demystifying 64 handles limit in WaitHandle.WaitAll</title>
		<link>http://bembengarifin.wordpress.com/2011/04/04/demystifying-64-handles-limit-in-waithandle-waitall/</link>
		<comments>http://bembengarifin.wordpress.com/2011/04/04/demystifying-64-handles-limit-in-waithandle-waitall/#comments</comments>
		<pubDate>Mon, 04 Apr 2011 17:12:38 +0000</pubDate>
		<dc:creator>Bembeng Arifin</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://bembengarifin.wordpress.com/?p=253</guid>
		<description><![CDATA[I have this doubt about this 64 handles limit recently for a while. We have been trying to increase the degree of parallelism in the existing application to optimize the performance and also to fully utilize the scaled out servers that we have on the grid. &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=253&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I have this doubt about this 64 handles limit recently for a while. We have been trying to increase the degree of parallelism in the existing application to optimize the performance and also to fully utilize the scaled out servers that we have on the grid.</p>
<p><a href="http://bembengarifin.files.wordpress.com/2011/04/parallel1.jpg"><img class="alignleft size-full wp-image-254" title="Parallel1" src="http://bembengarifin.files.wordpress.com/2011/04/parallel1.jpg?w=600" alt=""   /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>In the initial stage when I started the changes, I hit the following exception <span style="color:#ff0000;">System.NotSupportedException: The number of WaitHandles must be less than or equal to 64</span>. We then introduced some threshold limit for the degree of parallelism to avoid this exception. So all are working fine afterwards.</p>
<p>Now after one change to another, we started to see the opportunity of increasing the parallelism degree such as below, this brought me into a doubt where this 64 handles limitation is being applied (process / app domain level) and whether this recursive method will trigger the same issue if in the end we&#8217;re waiting for more than 64 handles for all layers.</p>
<p><a href="http://bembengarifin.files.wordpress.com/2011/04/parallel2.jpg"><img class="alignleft size-full wp-image-255" title="Parallel2" src="http://bembengarifin.files.wordpress.com/2011/04/parallel2.jpg?w=600" alt=""   /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Now if we <a href="http://msdn.microsoft.com/en-us/library/z6w25xa6.aspx" target="_blank">RTFM</a>, it basically says <i>&#8220;The WaitAll method returns when all the handles are signaled. On some implementations, if more than 64 handles are passed, a NotSupportedException is thrown&#8221;</i></p>
<p>Just to confirm this, I created a test below which will basically execute x number of high level parallel processes which will then also execute x number low level parallel processes based on the provided parameters. So the code below will try to create around 64 * 64 = 4096 handles in totals</p>
<p><pre class="brush: csharp;">
var p = new Processor();
p.DoProcess(hiLevelParallelism : 64, loLevelParallelism : 64);
</pre></p>
<p>Results<br />
<code><br />
05-Apr-2011 00:42:06.781 - Thead#13 - Start queueing 64 high level processes<br />
05-Apr-2011 00:42:06.815 - Thead#13 - Waiting for all 64 high level handles to complete<br />
05-Apr-2011 00:42:07.049 - Thead#17 - DoHighLevelProcess - Completed with 64 LowLeveProcesses<br />
05-Apr-2011 00:42:07.141 - Thead#15 - DoHighLevelProcess - Completed with 64 LowLeveProcesses<br />
05-Apr-2011 00:42:07.287 - Thead#24 - DoHighLevelProcess - Completed with 64 LowLeveProcesses<br />
..<br />
.. omitted 58 similar lines here<br />
..<br />
05-Apr-2011 00:42:08.087 - Thead#28 - DoHighLevelProcess - Completed with 64 LowLeveProcesses<br />
05-Apr-2011 00:42:08.179 - Thead#27 - DoHighLevelProcess - Completed with 64 LowLeveProcesses<br />
05-Apr-2011 00:42:08.297 - Thead#17 - DoHighLevelProcess - Completed with 64 LowLeveProcesses<br />
05-Apr-2011 00:42:08.455 - Thead#13 - All processes have been completed</code></p>
<p>It always feel much better if we see it running in the code, doesn&#8217;t it? :)</p>
<p>Source code<br />
<pre class="brush: csharp;">
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading;
using System.Diagnostics;

namespace ParallelismTests
{
    [TestClass]
    public class WaitHandleTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            var p = new Processor();
            p.DoProcess(hiLevelParallelism : 64, loLevelParallelism : 64);
        }
    }

    public class Processor
    {
        public void DoProcess(int hiLevelParallelism, int loLevelParallelism)
        {
            SetTurboMode();

            Debug(&quot;Start queueing {0} high level processes&quot;, hiLevelParallelism.ToString());

            var r = new Random();
            var hiLevelHandles = new AutoResetEvent[hiLevelParallelism];
            for (int i = 0; i &lt; hiLevelParallelism; i++)
            {
                var hiLevelHandle = new AutoResetEvent(false);
                hiLevelHandles[i] = hiLevelHandle;
                ThreadPool.QueueUserWorkItem((s) =&gt;
                {
                    DoHighLevelProcess(r, loLevelParallelism);
                    hiLevelHandle.Set();
                });
            }

            Debug(&quot;Waiting for all {0} high level handles to complete&quot;, hiLevelParallelism.ToString());
            WaitHandle.WaitAll(hiLevelHandles);

            Debug(&quot;All processes have been completed&quot;);
        }

        private void DoHighLevelProcess(Random r, int loLevelParallelism)
        {
            var loLevelHandles = new AutoResetEvent[loLevelParallelism];
            for (int i = 0; i &lt; loLevelParallelism; i++)
            {
                var loLevelHandle = new AutoResetEvent(false);
                loLevelHandles[i] = loLevelHandle;
                ThreadPool.QueueUserWorkItem((s) =&gt;
                {
                    DoLowLevelProcess(r.Next(1, 10));
                    loLevelHandle.Set();
                });
            }
            WaitHandle.WaitAll(loLevelHandles);

            Debug(&quot;DoHighLevelProcess - Completed with {0} LowLeveProcesses&quot;, loLevelParallelism);
        }
        private void DoLowLevelProcess(int Sleep)
        {
            Thread.Sleep(Sleep);
            //Debug(&quot;DoLowLevelProcess - Completed after {0} ms&quot;, Sleep.ToString());
        }

        /// &lt;summary&gt;
        /// oh i just wish the framework would have this in place like Console.WriteLine
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;format&quot;&gt;&lt;/param&gt;
        /// &lt;param name=&quot;&lt;span class=&quot; /&gt;args&quot;&gt;
        private static void Debug(string format, params object[] args)
        {
            System.Diagnostics.Debug.WriteLine(
                string.Format(&quot;{0} - Thead#{1} - {2}&quot;,
                    DateTime.Now.ToString(&quot;dd-MMM-yyyy HH:mm:ss.fff&quot;),
                    Thread.CurrentThread.ManagedThreadId.ToString(),
                    string.Format(format, args)));
        }
        /// &lt;summary&gt;
        /// This is not intended for production purpose
        /// &lt;/summary&gt;
        private static void SetTurboMode()
        {
            int t, io;
            ThreadPool.GetMaxThreads(out t, out io);
            Debug(&quot;Default Max {0}, I/O: {1}&quot;, t, io);

            var success = ThreadPool.SetMinThreads(t, io);
            Debug(&quot;Successfully set Min {0}, I/O: {1}&quot;, t, io);
        }
    }
}
</pre></p>
<br /> Tagged: <a href='http://bembengarifin.wordpress.com/tag/c/'>C#</a>, <a href='http://bembengarifin.wordpress.com/tag/multithreading/'>Multithreading</a>, <a href='http://bembengarifin.wordpress.com/tag/performance/'>performance</a>, <a href='http://bembengarifin.wordpress.com/tag/unit-test/'>unit test</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bembengarifin.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bembengarifin.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bembengarifin.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bembengarifin.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bembengarifin.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bembengarifin.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bembengarifin.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bembengarifin.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bembengarifin.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bembengarifin.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bembengarifin.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bembengarifin.wordpress.com/253/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bembengarifin.wordpress.com/253/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bembengarifin.wordpress.com/253/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=253&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://bembengarifin.wordpress.com/2011/04/04/demystifying-64-handles-limit-in-waithandle-waitall/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/16667ddc52caff2b1718e96fdcfc6e69?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bembengarifin</media:title>
		</media:content>

		<media:content url="http://bembengarifin.files.wordpress.com/2011/04/parallel1.jpg" medium="image">
			<media:title type="html">Parallel1</media:title>
		</media:content>

		<media:content url="http://bembengarifin.files.wordpress.com/2011/04/parallel2.jpg" medium="image">
			<media:title type="html">Parallel2</media:title>
		</media:content>
	</item>
		<item>
		<title>A flashback on Javascript</title>
		<link>http://bembengarifin.wordpress.com/2011/03/30/a-flashback-on-javascript/</link>
		<comments>http://bembengarifin.wordpress.com/2011/03/30/a-flashback-on-javascript/#comments</comments>
		<pubDate>Wed, 30 Mar 2011 13:26:21 +0000</pubDate>
		<dc:creator>Bembeng Arifin</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Slides]]></category>

		<guid isPermaLink="false">http://bembengarifin.wordpress.com/?p=246</guid>
		<description><![CDATA[After more than 2-3 years travelling to the WPF land, away from browser world, it&#8217;s nice to revisit Javascript once again. Tagged: Javascript, Slides<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=246&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>After more than 2-3 years travelling to the WPF land, away from browser world, it&#8217;s nice to revisit <a href="http://en.wikipedia.org/wiki/JavaScript" target="_blank">Javascript</a> once again.</p>
<iframe src='http://www.slideshare.net/slideshow/embed_code/5632538' width='600' height='492'></iframe>
<br /> Tagged: <a href='http://bembengarifin.wordpress.com/tag/javascript/'>Javascript</a>, <a href='http://bembengarifin.wordpress.com/tag/slides/'>Slides</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bembengarifin.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bembengarifin.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bembengarifin.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bembengarifin.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bembengarifin.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bembengarifin.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bembengarifin.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bembengarifin.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bembengarifin.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bembengarifin.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bembengarifin.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bembengarifin.wordpress.com/246/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bembengarifin.wordpress.com/246/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bembengarifin.wordpress.com/246/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=246&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://bembengarifin.wordpress.com/2011/03/30/a-flashback-on-javascript/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/16667ddc52caff2b1718e96fdcfc6e69?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bembengarifin</media:title>
		</media:content>
	</item>
		<item>
		<title>Extension over an extension for Dispatcher</title>
		<link>http://bembengarifin.wordpress.com/2011/03/24/extension-over-an-extension-for-dispatcher/</link>
		<comments>http://bembengarifin.wordpress.com/2011/03/24/extension-over-an-extension-for-dispatcher/#comments</comments>
		<pubDate>Thu, 24 Mar 2011 17:37:02 +0000</pubDate>
		<dc:creator>Bembeng Arifin</dc:creator>
				<category><![CDATA[Technical]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Multithreading]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://bembengarifin.wordpress.com/?p=235</guid>
		<description><![CDATA[I&#8217;m working on a migration of an existing winform control in our WPF app into a new WPF shiny control ;) Interestingly it was then breaking with the exception: The calling thread must be STA, because many UI components require this when trying to perform some action on the WPF control where it&#8217;s working fine [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=235&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m working on a migration of an existing winform control in our WPF app into a new WPF shiny control ;)</p>
<p>Interestingly it was then breaking with the exception:<span style="color:#ff0000;"> The calling thread must be STA, because many UI components require this</span> when trying to perform some action on the WPF control where it&#8217;s working fine for the existing winform version.</p>
<p>Turned out that this was due to the code was being invoked from a background thread through threadpool. Now it&#8217;s pretty easy to resolve this, we can use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.aspx" target="_blank">Dispatcher</a> property which is inherited by <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherobject.aspx" target="_blank">DispatcherObject</a> abstract class which is the base class of WPF <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.usercontrol.aspx" target="_blank">User Control</a>.</p>
<p><a href="http://bembengarifin.files.wordpress.com/2011/03/usercontrol-inheritance.jpg"><img class="alignleft size-full wp-image-236" title="UserControl Inheritance" src="http://bembengarifin.files.wordpress.com/2011/03/usercontrol-inheritance.jpg?w=600" alt=""   /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Now the Dispatcher class itself turned out to have a <a href="http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcherextensions.aspx" target="_blank">DispatcherExtensions</a> class (below) as well which accept Action type</p>
<p><a href="http://bembengarifin.files.wordpress.com/2011/03/dispatcherextensions.jpg"><img class="alignleft size-full wp-image-237" title="DispatcherExtensions" src="http://bembengarifin.files.wordpress.com/2011/03/dispatcherextensions.jpg?w=600" alt=""   /></a></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>So in order to fix the calling thread exception, we just need to have the following code.</p>
<p><pre class="brush: csharp;">
void OnSomeRequest()
{
    if (!Dispatcher.CheckAccess())
    {
        Dispatcher.Invoke(() =&gt; OnSomeRequest());
    }
    else
    {
        someUserControl.DoSomething();
    }
}
</pre></p>
<p><span style="font-family:Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;font-size:13px;line-height:19px;white-space:normal;">Now if we only have 1 certain place which will perform some UI update in the code, this is okay, but imagine if you have many places in the code that you need to repeat the pattern above :p</span></p>
<p>So we can simplify the above again into below, we have reduced the code from 8 lines into just 1 line :)</p>
<p><pre class="brush: csharp;">
void OnSomeRequest()
{
    Dispatcher.InvokeIfRequired(() =&gt; someUserControl.DoSomething());
}
</pre></p>
<p>The new extension over existing DispatcherExtension is simple.</p>
<p><pre class="brush: csharp;">
using System;
using System.Windows.Threading;

namespace ExtensionTests
{
    public static class AnotherDispatcherExtensions
    {
        public static void InvokeIfRequired(this Dispatcher dispatcher, Action action)
        {
            if (!dispatcher.CheckAccess())
            {
                dispatcher.Invoke(action);
            }
            else
            {
                action();
            }
        }
    }
}
</pre></p>
<p>Note that we can always add more extensions into this class, for me, I only have one above as I only require it, simple and only introduce when you need it :)</p>
<p>Eric De Carufel has written the more complete extensions as well in <a href="http://blog.decarufel.net/2009/03/good-practice-to-use-dispatcher-in-wpf.html" target="_blank">his blog post</a><br />
And if you&#8217;re wondering why VS intellisense is giving you a false alarm that CheckAccess is not available for Dispatcher, Claus Konrad explained it in <a href="http://blog.clauskonrad.net/2009/03/wpf-invokerequired-dispatchercheckacces.html" target="_blank">his blog post</a></p>
<br /> Tagged: <a href='http://bembengarifin.wordpress.com/tag/c/'>C#</a>, <a href='http://bembengarifin.wordpress.com/tag/multithreading/'>Multithreading</a>, <a href='http://bembengarifin.wordpress.com/tag/visual-studio/'>Visual Studio</a>, <a href='http://bembengarifin.wordpress.com/tag/wpf/'>WPF</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bembengarifin.wordpress.com/235/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bembengarifin.wordpress.com/235/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bembengarifin.wordpress.com/235/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bembengarifin.wordpress.com/235/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bembengarifin.wordpress.com/235/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bembengarifin.wordpress.com/235/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bembengarifin.wordpress.com/235/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bembengarifin.wordpress.com/235/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bembengarifin.wordpress.com/235/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bembengarifin.wordpress.com/235/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bembengarifin.wordpress.com/235/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bembengarifin.wordpress.com/235/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bembengarifin.wordpress.com/235/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bembengarifin.wordpress.com/235/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=bembengarifin.wordpress.com&amp;blog=3814076&amp;post=235&amp;subd=bembengarifin&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://bembengarifin.wordpress.com/2011/03/24/extension-over-an-extension-for-dispatcher/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/16667ddc52caff2b1718e96fdcfc6e69?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">bembengarifin</media:title>
		</media:content>

		<media:content url="http://bembengarifin.files.wordpress.com/2011/03/usercontrol-inheritance.jpg" medium="image">
			<media:title type="html">UserControl Inheritance</media:title>
		</media:content>

		<media:content url="http://bembengarifin.files.wordpress.com/2011/03/dispatcherextensions.jpg" medium="image">
			<media:title type="html">DispatcherExtensions</media:title>
		</media:content>
	</item>
	</channel>
</rss>
