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

<channel>
	<title>Luminis Software Development &#187; Floris Zwarteveen</title>
	<atom:link href="http://lsd.luminis.eu/author/florisz/feed/" rel="self" type="application/rss+xml" />
	<link>http://lsd.luminis.eu</link>
	<description></description>
	<lastBuildDate>Wed, 28 Dec 2011 20:44:50 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>nl</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Threading made easy in .Net 4.0 (1/2)</title>
		<link>http://lsd.luminis.eu/treading-made-ease-in-net-4-0/</link>
		<comments>http://lsd.luminis.eu/treading-made-ease-in-net-4-0/#comments</comments>
		<pubDate>Sat, 08 Jan 2011 12:27:22 +0000</pubDate>
		<dc:creator>Floris Zwarteveen</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://lsd.luminis.eu/?p=1356</guid>
		<description><![CDATA[.net threading threads system.threading.task twitter parallel 4.0 microsoft dotnet ]]></description>
			<content:encoded><![CDATA[<h3>Threading made Easy (1/2)</h3>
<p>In my opinion it isn’t possible to have these two words in one sentence. I’ve been exposed to thread programming numerous times in the past. Despite the almost heroic nature of being a ‘thread programmer’, I’ve never had the guts to expose this in public. Brag over a few beers about success stories on how well my thread-aware and thread-safe software was running? It has never been part of my vocabulary. One simple reason: it’s way too complicated. Well, at least for me. Even with the aid of thorough design, good examples and extensive mock tests my code remained complicated and incomprehensible. And yes, I tried to refactor, redesign, recode, restructure, whatever, I never could get it right.</p>
<p>Well, up until .Net 4 and its component: System.Threading.Tasks. Included in the very core of the framework. Right out of the box, support for threading for the masses.</p>
<h4>Why threading?</h4>
<p>It is good to step back for one moment. The 1-million-dollar-question to always ask yourself is: do I really need it? The simple answer is: yes. Because why would you let anyone wait while your machine is sitting there doing nothing? Especially when it is not necessary to wait.</p>
<blockquote><p>So: yes I need threading to make software as performant as can be to the best of my abilities as a software engineer.</p></blockquote>
<p>Do I always have to use threading? Of course not. In its most essential form, current CPU’s can do multiple things at the same time (especially when having more cores) and are very fast and therefore often waiting for some other things (like database or web I/O stuff) to end before they can continue. So if you’re in such a situation, and I can assure you, this is most often, threads come to the rescue to really utilize the CPU to its full capacity.</p>
<h4>The example</h4>
<p>Let’s apply threading to a simple example to show how the new .Net threadinglayer can be utilized to increase performance 40-70% in a very easy manner.</p>
<p>Suppose you want to do a multiple query on Twitter (most popular demo environment) in which you need to return the first 100 hits for a couple of subjects. I have tried this with my webbrowser and you have to do some manual work to return such a list in one piece.</p>
<p>Beforehand I do know getting 100 tweets from Twitter isn’t that difficult, especially with their JSON based REST API (that’s a lot of cool keywords in one sentence!). So one task is easy to implement. I also know that getting something from the internet usually sets my CPU in a comfortable waiting state because network transfer is still way slower than my CPU. So the task is also suitable for multiplexing a couple of times.</p>
<h4>Some preparation</h4>
<p>First I have to define my testcases. I don’t want to get bogged down into testclasses (although I do agree it would have been better to use them) because hey, this is demo code anyway.</p>
<p>The thing I want to show you is:<br />
<img class="alignnone size-full wp-image-1390" title="ThreadingScenario" src="http://lsd.luminis.eu/wp-content/uploads/2011/01/ThreadingScenario.png" alt="ThreadingScenario" width="284" height="219" /><br />
In short, I want to show the performance differences between four separate scenarios<br />
-      A non threaded one<br />
-      A classic, pre 4.0, threadpool version<br />
-      A 4.0 version using the new TaskFactory<br />
-      And finally the version using the new Parallel class</p>
<p>These scenarios all do exactly the same thing; only the scheduling of the tasks differs. The thing they have to do is get some data from the web in the following pseudo manner:<br />
<code><br />
foreach subject from the list<br />
search for the last 100 tweets on this subject<br />
</code></p>
<p>The search API in Twitter is pretty straightword. For example, to perform the above for the subject ‘luminis’ the following url will suffice:</p>
<p><code>http://search.twitter.com/search.json?&amp;q=luminis&amp;rpp=100<br />
</code><br />
To get data from the web I’ve defined a small routine which returns a byte array with the required data. Fortunately WCF made getting data from the web pretty straightforward in .Net, this resulted in the very simple basic routine:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> Get<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> url<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">byte</span><span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> data <span style="color: #008000;">=</span> null<span style="color: #008000;">;</span>
    WebClient wc <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> WebClient<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">try</span>
    <span style="color: #000000;">&#123;</span>
        data <span style="color: #008000;">=</span> wc.<span style="color: #0000FF;">DownloadData</span><span style="color: #000000;">&#40;</span>url<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">catch</span>
    <span style="color: #000000;">&#123;</span>
        <span style="color: #008080; font-style: italic;">// probable time out, for this demo just quit</span>
    <span style="color: #000000;">&#125;</span>
    <span style="color: #0600FF;">finally</span>
    <span style="color: #000000;">&#123;</span>
        wc.<span style="color: #0000FF;">Dispose</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF;">return</span> data<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>This routine is part of a class called WebContent. This class also has a public property UrlList which can contain the list of urls for which the content must be read.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> List _UrlList <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> List UrlList
<span style="color: #000000;">&#123;</span>
    get
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">return</span> _UrlList<span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>What I have to do now is to iterate over this list and call my simple Get routine for each of the four scenarios.</p>
<h4>#1: The non-threaded version</h4>
<p>The simple version is the one without any threading at all. We do need this one to baseline our tests so we can do a comparison with the threaded counterparts. The only thing we need to do is read all the urls and the code pretty much resembles the pseudo code shown previously:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> GetSequential<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> url <span style="color: #0600FF;">in</span> UrlList<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        Get<span style="color: #000000;">&#40;</span>url<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<h4>#2: The 2.0 ThreadPool version</h4>
<p>Actually I didn’t want to make the ThreadPool version because as said earlier I don’t get this ‘old’ thread programming very well. But as a reference I’ve hacked a version for which I can’t take any liabilities. It is just here for reference purposes. Note that I need two routines to achieve the same goal. Additionally I’ve changed the thread of the main to [MTAThreadAttribute] otherwise you will receive to message:<br />
<img class="aligncenter size-full wp-image-1393" title="PerfSTAError" src="http://lsd.luminis.eu/wp-content/uploads/2011/01/PerfSTAError.png" alt="PerfSTAError" width="456" height="236" /><br />
Anyway the code looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> GetWithThreadPool<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    _ResetEvents <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ManualResetEvent<span style="color: #000000;">&#91;</span>UrlList.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
    Random rand <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Random<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF;">for</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> i <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span> i <span style="color: #008000;">&amp;</span>lt<span style="color: #008000;">;</span> UrlList.<span style="color: #0000FF;">Count</span><span style="color: #008000;">;</span> i<span style="color: #008000;">++</span><span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        _ResetEvents<span style="color: #000000;">&#91;</span>i<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> ManualResetEvent<span style="color: #000000;">&#40;</span><span style="color: #0600FF;">false</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        ThreadPool.<span style="color: #0000FF;">QueueUserWorkItem</span><span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> WaitCallback<span style="color: #000000;">&#40;</span>DoThreadPoolWork<span style="color: #000000;">&#41;</span>, <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span><span style="color: #000000;">&#41;</span>i<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    WaitHandle.<span style="color: #0000FF;">WaitAll</span><span style="color: #000000;">&#40;</span>_ResetEvents<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> DoThreadPoolWork<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> o<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #FF0000;">int</span> index <span style="color: #008000;">=</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span><span style="color: #000000;">&#41;</span>o<span style="color: #008000;">;</span>
&nbsp;
    Get<span style="color: #000000;">&#40;</span>UrlList<span style="color: #000000;">&#91;</span>index<span style="color: #000000;">&#93;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    _ResetEvents<span style="color: #000000;">&#91;</span>index<span style="color: #000000;">&#93;</span>.<span style="color: #0000FF;">Set</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Pretty impressive but incomprehensible, huh?<br />
It doesn&#8217;t feel right that you have to add all these complex things just to get a bit of multi-threading. To me, the only easy part is the Get call somewhere near the end. All the other stuff is thread overhead. And if you would need more that 25 threads this code won’t work. But let’s not dwell on these passed issues and move over to the 4.0 versions.</p>
<h4>#3: The  4.0 TaskFactory version</h4>
<p>The task factory shows what the thread overhead could be if the framework is more powerful than the 2.0 version. Still it is some overhead but the code looks more like the pseudo code than the previous implementation:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> GetWithTaskFactory<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Task<span style="color: #000000;">&#91;</span><span style="color: #000000;">&#93;</span> tasks <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Task<span style="color: #000000;">&#91;</span>UrlList.<span style="color: #0000FF;">Count</span><span style="color: #000000;">&#93;</span><span style="color: #008000;">;</span>
    <span style="color: #FF0000;">int</span> counter <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">foreach</span> <span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> url <span style="color: #0600FF;">in</span> UrlList<span style="color: #000000;">&#41;</span>
    <span style="color: #000000;">&#123;</span>
        var task <span style="color: #008000;">=</span> Task.<span style="color: #0000FF;">Factory</span>.<span style="color: #0000FF;">StartNew</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span>
                                 Get<span style="color: #000000;">&#40;</span>url<span style="color: #000000;">&#41;</span>, TaskCreationOptions.<span style="color: #0000FF;">LongRunning</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        tasks<span style="color: #000000;">&#91;</span>counter<span style="color: #000000;">&#93;</span> <span style="color: #008000;">=</span> task<span style="color: #008000;">;</span>
        counter<span style="color: #008000;">++;</span>
    <span style="color: #000000;">&#125;</span>
&nbsp;
    Task.<span style="color: #0000FF;">WaitAll</span><span style="color: #000000;">&#40;</span>tasks<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The thing I need to do is to create a task for each subject and, with a lambda expression, call my good old private Get() on this task. Finally I just have to wait until all tasks are finished.</p>
<h4>#4: The 4.0 Parallel version</h4>
<p>The ultimate version is left to the end. The new Parallel class makes it possible to write threaded code without almost no (thread) overhead. It looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> GetParallel<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    Parallel.<span style="color: #0600FF;">ForEach</span><span style="color: #000000;">&#40;</span>UrlList, url <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span>
        <span style="color: #000000;">&#123;</span>
            Get<span style="color: #000000;">&#40;</span>url<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Isn’t that just beautiful? It also resembles the pseudo code pretty well. Okay you have to understand the lambda expression with the anonymous delegate syntax and semantics but if you do it is just an ordinary for-loop. As far as I’m concerned: this is as it should be.</p>
<h4>Performance results</h4>
<p>So far the differences in the source code of the four implementations. To start each of the separate scenarios a little bit of timing code is needed to calculate the total of milliseconds the code runs.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #FF0000;">delegate</span> <span style="color: #0600FF;">void</span> GetContentDelegate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">string</span> DoTimedOperation<span style="color: #000000;">&#40;</span>GetContentDelegate getForumContentDelegate<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    DateTime start <span style="color: #008000;">=</span> DateTime.<span style="color: #0000FF;">Now</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">// perform the actual operation</span>
    getForumContentDelegate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    DateTime end <span style="color: #008000;">=</span> DateTime.<span style="color: #0000FF;">Now</span><span style="color: #008000;">;</span>
    TimeSpan elapsed <span style="color: #008000;">=</span> end <span style="color: #008000;">-</span> start<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">return</span> elapsed.<span style="color: #0000FF;">TotalMilliseconds</span>.<span style="color: #0000FF;">ToString</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span> <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;ms&quot;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>And with the aid of a delegate the timing function is called four times as in:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> StartSequential_Click<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">lblSequentialTime</span>.<span style="color: #0000FF;">Text</span> <span style="color: #008000;">=</span>
        DoTimedOperation<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> GetContentDelegate<span style="color: #000000;">&#40;</span>WebContent.<span style="color: #0000FF;">GetSequential</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> StartThreadPool_Click<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">lblThreadPoolTime</span>.<span style="color: #0000FF;">Text</span> <span style="color: #008000;">=</span>
        DoTimedOperation<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> GetContentDelegate<span style="color: #000000;">&#40;</span>WebContent.<span style="color: #0000FF;">GetWithThreadPool</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> StartTaskFactoryl_Click<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">lblTaskFactoryTime</span>.<span style="color: #0000FF;">Text</span> <span style="color: #008000;">=</span>
        DoTimedOperation<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> GetContentDelegate<span style="color: #000000;">&#40;</span>WebContent.<span style="color: #0000FF;">GetWithTaskFactory</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span>
&nbsp;
<span style="color: #0600FF;">private</span> <span style="color: #0600FF;">void</span> StartParallel_Click<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">object</span> sender, EventArgs e<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">this</span>.<span style="color: #0000FF;">lblParallelTime</span>.<span style="color: #0000FF;">Text</span> <span style="color: #008000;">=</span>
        DoTimedOperation<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> GetContentDelegate<span style="color: #000000;">&#40;</span>WebContent.<span style="color: #0000FF;">GetParallel</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>I ran a few tests on my machine and one of them resulted in the following numbers: (By the way my machine is a Macbook Pro running Windows 7 in a Virtual Box with 1 processor and 2048 Mb memory.)<br />
<img class="aligncenter size-full wp-image-1394" title="PerfResults" src="http://lsd.luminis.eu/wp-content/uploads/2011/01/PerfResults.png" alt="PerfResults" width="284" height="217" /><br />
Of course you have to try this on your own machine but it is safe to say that the performance increase is worth the overhead in thread programming.</p>
<p>I have analyzed the thread behavior with the Performance Monitor (PerfMon). In the analysis I was interested in:<br />
-      # of processor threads (blue)<br />
-      # of logical threads for the process (green)<br />
-      # of physical threads for the process (red)<br />
These are the results of one test I have run:<br />
<img class="aligncenter size-full wp-image-1396" title="Dia1" src="http://lsd.luminis.eu/wp-content/uploads/2011/01/Dia1.jpg" alt="Dia1" width="720" height="434" /><br />
You can see the framework too needs some threads when the non threaded version is started. When the threadpool scenario starts you clearly see the increase in threads. The threadpool is managed by .Net so this amount doesn&#8217;t decrease when the scenario is finished. This does happen with the third scenario. Here the threads are in control of the routine and you can clearly see that the threads are released (at least to the system, the framework has a different view on it). In the fourth scenario again the threads are fully controlled by the framework.<br />
Interesting to see is: in both the threadpool and the parallel scenario only a limited amount of threads are created (approximately 5 or 6) while in the Taskfactory 12 threads are created (for each subject one). It is hard to say what exactly happens behind the scenes. Do all logical threads have a physical thread associated? And do these threads run &#8217;simultaneously&#8217; or not? I have to say I don&#8217;t know.<br />
Then there is one thing I don&#8217;t understand at all. How is it possible (near the end) that the total number of physical threads of the process is higher than the system amount of physical threads?! If somebody can tell me this I would be very hapy!</p>
<h4>Conclusion</h4>
<p>In a next blog I will extend this little example. So far I have concentrated on threads, starting and synchronizing them to show the performance differences. I have experimental proof it is worth taking an effort to learn more on the new .Net 4.0 threading stuff.<br />
The part that is left out is the handling of the data and the presentation of the results.<br />
This part is described in part 2 and can be found <a href="http://lsd.luminis.eu/threading-made-easy-in-net-4-0-22/">here</a>.</p>
<p>have fun, florisz</p>
<p>Download the zip for the full source code <a href="http://lsd.luminis.eu/wp-content/uploads/2011/01/ThreadingTest.zip">here</a>.</p>
<h4>References</h4>
<p><a href="http://apiwiki.twitter.com/w/page/22554756/Twitter-Search-API-Method:-search">Twitter Search API</a></p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.aspx">MSDN on System.Threading.Tasks</a></p>
<p><a href="http://www.codethinked.com/post/2010/01/25/NET-40-and-SystemThreadingTasks.aspx">.Net 4.0 and System.Threading.Tasks</a></p>
<p><a href="http://www.switchonthecode.com/tutorials/csharp-tutorial-using-the-threadpool">Threadpool example</a></p>
<p><a href="http://www.eggheadcafe.com/tutorials/aspnet/21013a52-fe11-4af8-bf8b-50cfd1a51577/task-parallelism-in-c-40-with-systemthreadingtasks.aspx">Task Parallelism in C# 4.0 with System.Threading.Tasks</a></p>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.eu/treading-made-ease-in-net-4-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java .Net interoperability</title>
		<link>http://lsd.luminis.eu/java-net-interoperability/</link>
		<comments>http://lsd.luminis.eu/java-net-interoperability/#comments</comments>
		<pubDate>Mon, 01 Jun 2009 20:49:45 +0000</pubDate>
		<dc:creator>Floris Zwarteveen</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[assemblyresolving]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[call]]></category>
		<category><![CDATA[interoperability]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jni]]></category>
		<category><![CDATA[methods]]></category>
		<category><![CDATA[nameresolving]]></category>

		<guid isPermaLink="false">http://lsd.luminis.net/?p=202</guid>
		<description><![CDATA[<img class="nieuws_post_image" src="http://blog.luminis.nl/luminis/resource/thumbnails/java2dotnetthumbnail.jpg">How to call C# methods in the most straightforward way from within a java class. This is realized with the aid of JNI and without .Net remoting, webservices or COM bridges.]]></description>
			<content:encoded><![CDATA[<h1>Java .Net interoperability</h1>
<p>
Have you ever felt the urge and need to connect your Java program to a particular .Net assembly? And more specifically without the hassle of COM bridges, web services, .Net remoting or other service type components. I came across a project in which a simple Java program needed to be connected to an existing .Net assembly (btw written in C#). Everything had to be as simple as possible.<br />
On the Internet a couple of articles were helpful: Espresso, C# method calls within Java Program and Calling a .NET Method from Java via JNI. However it didn’t quite work the way we liked so the ulimate solution came (it so often happens) from Jelle Hissink (http://www.codewise.nl)
</p>
<p>The solution is based on:</p>
<ul>
<li>Use JNI for the communication between the Java VM and the .Net CLR</li>
<li>Intercept the call to the name resolver and resolve the call to the C# class with your own method</li>
</ul>
<p>Graphically this looks like:<br />
<img width="480px" src="http://blog.luminis.nl/roller/luminis/resource/florisz/java2dotnetpicture1.jpg"/></p>
<p>Let’s work our way from the initial Java call to the final C# implementation.</p>
<h3>Java</h3>
<p>
In Java we have the simple program:
</p>
<pre>
class HelloWorld {
   public static void main(String[] args)
  {
      DotNetBridge dotNetBridge = new DotNetBridge();
      String getString = dotNetBridge.GetString();
      System.out.println("GetString() returned:   " + getString);

      String newString = "Java2.Net world";
      dotNetBridge.SetString(newString);
	getString = dotNetBridge.GetString();
      System.out.println("GetString() returned:   " + getString);
   }
}
</pre>
<p>
Nothing special, just straightforward java code.<br />
However in addition to this code we define an extra class with the DotNetBridge code on the java side. This is needed to kick start the bridging.
</p>
<pre>
public class DotNetBridge
{
  private native void Initialize(String localPath);
  public native String GetString();
  public native void SetString(String newString);

  static
  {
    String path = DotNetBridge.class.getProtectionDomain().getCodeSource().getLocation().getPath();
    int idx = path.lastIndexOf("/");
    if (idx >= 0) {
      path = path.substring(0, idx);
    }
    if (path.startsWith("/")) {
      path = path.substring(1);
    }

    System.load(path + "/DotNetBridge.dll");
    DotNetBridge dotNetBridge = new DotNetBridge();
    dotNetBridge.Initialize(path);
  }
}
</pre>
<p>
In a few words what does it do? It is a class with native methods telling the java compiler that it can find the interface of the methods in this class but the implementation is to be found in a native Windows dll file. On top of that when to class is instantiated for the first time the static part will ensure that the Initialize method is called in which the full path of the dll file with the implementation is passed. Be a little more patient, later on we’ll see why we need this.
</p>
<h3>DotNetBridge</h3>
<p>
We now need a simple interface from the Java to the .Net world in which strings can be passed in and out. For this purpose we create a managed C++ project in Visual Studio of the name DotNetBridge. The project consists of:</p>
<ul>
<li>A C++ header file with the definition of the bridge interface</li>
<li>A C++ file with the implementation of the bridge</li>
<li>A reference to the .Net component with the implementation of the actual HelloWorld code</li>
</ul>
<p>
The header file DotNetBridge.h makes use of JNI (ofcourse) to define the interface of the bridge:
</p>
<pre>
#include "jni.h"

JNIEXPORT void JNICALL Java_DotNetBridge_Initialize(JNIEnv *env, jobject thisobject, jstring localPath);
JNIEXPORT jstring JNICALL Java_DotNetBridge_GetString(JNIEnv *env, jobject thisobject);
JNIEXPORT void JNICALL Java_DotNetBridge_SetString(JNIEnv *env, jobject thisobject, jstring newString);
</pre>
<p>
I’ll not dive into the details of  JNI too much (see JNI Primer) but this is the most minimal definition. There are tools to generate this type of definitions (javah –jni) but we leave those out of the equation today. For now watch the prefix Java_DotNetBridge_ which are needed in case of JNI. Also the env and thisobject parameters are specific for each JNI call.
</p>
<p>
The implementation in C++ has become much more easily with the new .Net framework primitives for managed C++. The two main methods on the interface are the get and set string methods, their implementation looks like:
</p>
<pre>
using namespace System;
using namespace System::Runtime::InteropServices;
using namespace HelloWorldDotNet;

#include <string>

JNIEXPORT jstring JNICALL
Java_DotNetBridge_GetString (JNIEnv *env, jobject thisobject)
{
    IHelloWorld ^support = gcnew HelloWorld();

    // Get a managed string.
    String ^managedString = support->GetString();

    std::string str = managedToString(managedString);

    // Create the java string...
    jstring result = env->NewStringUTF(str.c_str());

    return result;
}

JNIEXPORT void JNICALL
Java_DotNetBridge_SetString (JNIEnv *env, jobject thisobject,
								jstring newString)
{
    IHelloWorld ^support = gcnew HelloWorld();

    std::wstring newWString = jstringToWString(env, newString);

    String ^ managedString = gcnew String(newWString.c_str());

    support->SetString(managedString);
}
</pre>
<p>
To enable all this we do need some extra string management functions which can translate the java formatted strings to .Net strings and vice versa. Also the transition from the managed to unmanaged environment has its effect on the string management as can be seen from:
</p>
<pre>
std::wstring jstringToWString(JNIEnv *env, jstring jstr)
{
  jboolean iscopy;
  const jchar *strPtr = env->GetStringChars(jstr, &#038;iscopy);

  const jchar *p = strPtr;
  std::wstring result;
  while (*p)
  {
    result += *(p++);
  }

  env->ReleaseStringChars(jstr, strPtr);

  return result;
}

std::string managedToString(String ^mstr)
{
  // Marshal the managed string to unmanaged memory.
  IntPtr hGlobal = Marshal::StringToHGlobalAnsi(mstr);

  char *stringPointer = static_cast<char *>(hGlobal.ToPointer());

  // Create the java string...
  std::string result = stringPointer;

  // Always free the unmanaged string.
  Marshal::FreeHGlobal(hGlobal);

  return result;
}
</pre>
<p>
Finally, as said earlier, we need to kick start the whole mechanism. Hence the managed C++ code has currently no idea where to find an implementation of the HelloWorld class in the call to: IHelloWorld ^support = gcnew HelloWorld();<br />
By the way, the import of the namespace has sneaked into the C++ code quite silently with: using namespace HelloWorldDotNet; Without setting a reference to the .Net assembly in the projects’ properties the compiler will not be able to compile this C++ class. Setting such a reference can be done with:
</p>
<p><img width="480px" src="http://blog.luminis.nl/roller/luminis/resource/florisz/java2dotnetpicture3.png"/></p>
<p>
In the Java implementation we have seen that each instantiation of the java bridge class results in a call to the initialize function of the DotNetBridge component. Finally it is time to dive into the details of its implementation. We could have done without it if we deploy all dlls to the java executable directories. From a administration perspective this is not very neat. System administrators normally require that a solution is delivered to one location and the software should take care of its own path settings.
</p>
<p>
In essence the initialize function of the DotNetBridge is always called once and exactly once with the full path specification of the actual executable directory. So put all dlls into this directory and intercept the name resolver. Because if the runtime tries to load the assembly with the implementation of the HelloWorld class it should look into one specific dll to find this implementation. So this will happen:</p>
<ul>
<li>On the initialize the directory path of the HelloWorld.dll is stored in a static variable</li>
<li>The AssemblyResolve event is augmented with its own handler</li>
<li>In the handler the directory path is used to load the HelloWorld class from the correct dll</li>
</ul>
<pre>
std::wstring assemblyLoadPath;

System::Reflection::Assembly ^ MyResolveEventHandler( Object^ sender, ResolveEventArgs^ args )
{
  String ^name = args->Name;
  int idx = name->IndexOf(L',');
  if (idx >= 0) {
    name = name->Substring(0, idx);
  }
  name = String::Concat(name, gcnew String(L".dll"));

  String ^basePath = gcnew String(assemblyLoadPath.c_str());
  name = System::IO::Path::Combine(basePath, name);

  System::Reflection::Assembly ^ result = System::Reflection::Assembly::LoadFile(name);

  return result;
}

JNIEXPORT void JNICALL Java_DotNetBridge_Initialize (JNIEnv *env, jobject thisobject, jstring localPath)
{
    assemblyLoadPath = jstringToWString(env, localPath);

    AppDomain ^currentDomain = AppDomain::CurrentDomain;
    currentDomain->AssemblyResolve += gcnew ResolveEventHandler( MyResolveEventHandler );
}
</pre>
<p>
This will do the trick on the .Net bridge side. The final implementation of the C# code is straightforward.
</p>
<h3>C# code</h3>
<p>
It is a C# class library project. It consists of two classes: the interface and its implementation. The code of the interface definition looks like:
</p>
<pre>
using System;

namespace HelloWorldDotNet
{
    public interface IHelloWorld
    {
        void SetString(string stringValue);
        string GetString();
    }
}
</pre>
<p>
Finally its implementation can be anything. In this case it is simple as:
</p>
<pre>
using System;

namespace HelloWorldDotNet
{
    public class HelloWorld : IHelloWorld
    {
        private static string lastString = "brave new world";
        public void SetString(string stringValue)
        {
            lastString = stringValue;
        }
        public string GetString()
        {
            return String.Format("Hello {0}", lastString);
        }
    }
}
</pre>
<h3>Finally</h3>
<p>
On purpose, in the code examples details such as exception handling and comments were left out. If you’re interested you can download all the code (see below). On the java side DOS command scripts are used to compile and run the example. You’ll find them easy and straightforward. The C++ and C# code are organized in two separate .Net projects. They were made with Visual Studio 2008. Either migrate to Studio 2008 or use the source code files to build a solution yourself.<br />
If you can’t find your way through all the source files, this is the rough organization:
</p>
<p><img width="480px" src="http://blog.luminis.nl/roller/luminis/resource/florisz/java2dotnetpicture2.jpg"/></p>
<p>
These are the main steps, with their correct order, to get it to work:
</p>
<ul>
<li>Compile the HelloWorld C# project</li>
<li>From the DotNetBridge project set the reference to the HelloWorld.dll created in the previous step</li>
<li>(possibly) in the DotNetBridge project set the include directories to include the path to the correct JVM include directories (otherwise the jni.h can not be found)</li>
<li>Compile the DotNetBridge project</li>
<li>Change the compile.cmd and run.cmd scripts in the Java directory to reflect the correct paths.</li>
<li>Run compile.cmd</li>
<li>Run run.cmd</li>
<p>
If unchanged you should see something like:
</p>
<p><img width="480px" src="http://blog.luminis.nl/roller/luminis/resource/florisz/java2dotnetpicture4.png"/><br />
</br><br />
</br></p>
<p>
When you want a full download of all the code in this sample, click <b><a href="http://blog.luminis.nl/roller/luminis/resource/florisz/Java2DotNet.zip">here</a></b>.
</p>
<p>
And last but not least: have fun!</p>
]]></content:encoded>
			<wfw:commentRss>http://lsd.luminis.eu/java-net-interoperability/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

