<?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>The Inquisitive Coder - Davy Brion&#039;s Blog &#187; Asynchronous Programming</title> <atom:link href="http://davybrion.com/blog/category/asynchronous-programming/feed/" rel="self" type="application/rss+xml" /><link>http://davybrion.com/blog</link> <description>inquisitive: adjective. given to inquiry, research, or asking questions; eager for knowledge; intellectually curious</description> <lastBuildDate>Mon, 14 May 2012 21:08:36 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.2</generator> <item><title>Calling Synchronous Methods Asynchronously</title><link>http://davybrion.com/blog/2008/06/calling-synchronous-methods-asynchronously/</link> <comments>http://davybrion.com/blog/2008/06/calling-synchronous-methods-asynchronously/#comments</comments> <pubDate>Wed, 04 Jun 2008 09:03:56 +0000</pubDate> <dc:creator>Davy Brion</dc:creator> <category><![CDATA[Asynchronous Programming]]></category> <category><![CDATA[Performance]]></category><guid
isPermaLink="false">http://davybrion.com/blog/?p=134</guid> <description><![CDATA[Calling expensive synchronous methods in succession can sometimes waste a lot of time. If those synchronous methods spend most of their time waiting on external resources, you're probably better off executing those methods at the same time and waiting for all the results to come back instead of executing a method, waiting for its result, [...]]]></description> <content:encoded><![CDATA[<p>Calling expensive synchronous methods in succession can sometimes waste a lot of time.  If those synchronous methods spend most of their time waiting on external resources, you're probably better off executing those methods at the same time and waiting for all the results to come back instead of executing a method, waiting for its result, executing the next method, waiting for that ones result, etc...</p><p>take this code for instance:</p><div><pre class="brush: csharp; title: ; notranslate">
            List&lt;UserPrincipal&gt; users = activeDirectoryFacade.GetAllUsers();
            List&lt;GroupPrincipal&gt; groups = activeDirectoryFacade.GetAllGroups();
</pre></div><p>Both calls can take a while, and they spend practically all of their time waiting on an external resource. Unfortunately, in this case neither method has an asynchronous implementation. You've probably seen that a lot of .NET classes offer asynchronous implementations of some methods along with their synchronous implementations. If there's an Xxx method, the asynchronous methods will be named BeginXxx and EndXxx.  This can be very useful at times, but if no asynchronous method is available for the task you need to do, how do you effectively perform that task asynchronously?</p><p>It's not that hard... so let's give it a shot. First of all, we need to define the methods that we want to execute:</p><div><pre class="brush: csharp; title: ; notranslate">
            Func&lt;List&lt;UserPrincipal&gt;&gt; fetchUsers = () =&gt; activeDirectoryFacade.GetAllUsers();
            Func&lt;List&lt;GroupPrincipal&gt;&gt; fetchGroups = () =&gt; activeDirectoryFacade.GetAllGroups();
</pre></div><p>The GetAllUsers method is now defined as a function that returns a List of UserPrincipals. The GetAllGroups method is now defined as a function that returns a List of GroupPrincipals.  And now we can simply call them asynchronously like this:</p><div><pre class="brush: csharp; title: ; notranslate">
            IAsyncResult fetchUserAsyncResult = fetchUsers.BeginInvoke(null, null);
            IAsyncResult fetchGroupsAsyncrResult = fetchGroups.BeginInvoke(null, null);
</pre></div><p>The BeginInvoke method invokes the original method, but instead of waiting for the original method to finish, it immediately returns with an IAsyncResult instance which we'll use later on. The first parameter of the BeginInvoke method is an AsyncCallback instance, the second one can be any object that you want to pass along to the AsyncCallback.  The AsyncCallback is just another method that will be called when the original method has completed its task.  In this case, we don't use a callback so we simply pass null.</p><p>So now both original methods are executing, and our code needs to wait for the result.  We can either call the EndInvoke method on the Func instances, which will block until the original method has completed, or we can explicitely wait using a waithandle offered by the returned IAsyncResult:</p><div><pre class="brush: csharp; title: ; notranslate">
            fetchUserAsyncResult.AsyncWaitHandle.WaitOne();
            fetchGroupsAsyncrResult.AsyncWaitHandle.WaitOne();
 
            List&lt;UserPrincipal&gt; userPrincipals = fetchUsers.EndInvoke(fetchUserAsyncResult);
            List&lt;GroupPrincipal&gt; groupPrincipals = fetchGroups.EndInvoke(fetchGroupsAsyncrResult);
</pre></div><p>In this case, calling the WaitOne method of the waithandle blocks the current thread until the original method has finished its task. Keep in mind that while you wait on the first method, the second one might still be executing as well.  Waiting on the first method does not influence the execution of the second method at all.</p><p>So in the above piece of code, we explicitly wait for both methods to finish.  And then we call the EndInvoke method and pass the IAsyncResult to it, which will complete the entire operation and returns the return value of the original method.  We could've just as easily skipped calling the WaitOne method on the waithandles, and the call to EndInvoke would've blocked until the original method had finished as well.  However, i think the calls to WaitOne make the intent of the code more clear which makes the code easier to understand.</p><p>Anyways, as you can see, it's trivially easy to perform synchronous methods in an asynchronous manner.  This can sometimes offer tremendous advantages for performance, but you shouldn't go around using this all the time.  It only offers a benefit if you have a slow method somewhere and you can actually do some other work as well while the slow method is executing.</p><div
class="bottomcontainerBox" style=""><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <iframe
src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fdavybrion.com%2Fblog%2F2008%2F06%2Fcalling-synchronous-methods-asynchronously%2F&amp;layout=button_count&amp;show_faces=false&amp;width=85&amp;action=like&amp;font=verdana&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:85px; height:21px;"></iframe></div><div
style="float:left; width:80px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <g:plusone size="medium" href="http://davybrion.com/blog/2008/06/calling-synchronous-methods-asynchronously/"></g:plusone></div><div
style="float:left; width:95px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"> <a
href="http://twitter.com/share" class="twitter-share-button" data-url="http://davybrion.com/blog/2008/06/calling-synchronous-methods-asynchronously/"  data-text="Calling Synchronous Methods Asynchronously" data-count="horizontal" data-via="davybrion"></a></div><div
style="float:left; width:105px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script type="in/share" data-url="http://davybrion.com/blog/2008/06/calling-synchronous-methods-asynchronously/" data-counter="right"></script></div><div
style="float:left; width:85px;padding-right:10px; margin:4px 4px 4px 4px;height:30px;"><script src="http://www.stumbleupon.com/hostedbadge.php?s=1&amp;r=http://davybrion.com/blog/2008/06/calling-synchronous-methods-asynchronously/"></script></div></div><div
style="clear:both"></div><div
style="padding-bottom:4px;"></div>]]></content:encoded> <wfw:commentRss>http://davybrion.com/blog/2008/06/calling-synchronous-methods-asynchronously/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced
Database Caching 2/11 queries in 0.004 seconds using disk: basic
Object Caching 370/379 objects using disk: basic
Content Delivery Network via Amazon Web Services: CloudFront: d18sni7re4ly7f.cloudfront.net

Served from: davybrion.com @ 2012-05-23 13:40:47 -->
