Wednesday, February 4, 2009

Improve Performance with Asynchronus processing, Anonymous methods and Thread Pools.


Read more about this article at my web site.

The very first week in my new group, I was asked if I could improve the performance of a loop in a method that was being called from the business logic façade of an application. The purpose of the loop was to synthesize data back and forth between custom objects fetched from the data layer into similar but incompatible custom objects in the business layer. I know what you’re thinking… pretty standard OOP stuff from around 2001, but you probably also know that this stuff requires good code familiarity due to the symbiotic relationship that exists between all of the moving parts. To make things even more difficult, some of the properties in those objects were actually returning collections of other incompatible objects that needed to be synthesized back and forth as well.

I decided that the best course of action would probably be to focus on the loop itself. I knew that the loop iterated through a collection of objects and converted them to a collection of other objects, and I knew that the collection could be potentially large so I figured that I could get some immediate performance improvement by simply populating the objects in the loop asynchronously versus in-line.

The first thing I needed was a baseline performance count. I need to get a count In milliseconds of how long the loop alone took to complete without the fetch operation, which could skew the statistics by as much as 50%. In the old days of 1.1 I used to have to import the QueryPerformanceCounter class in the Kernel32 library and run start, stop and clear operations and calculate the totals. http://msdn2.microsoft.com/en-us/library/ms979201.aspx

Today however we can do the same thing with the Stopwatch class in the System.Diagnostics library with 2 commands, Start and Stop. Don’t forget to write the output from the stopwatch using a formatted string and ToString() the ElapsedMiliseconds property to avoid boxing operations.

Let’s look at a mock up of the code:

http://msdn2.microsoft.com/en-us/library/0ka9477y.aspx"> >http://msdn2.microsoft.com/en-us/library/0ka9477y.aspx

We will need to ensure that control is not returned to the calling method until the thread pool is finished and we have several options available to us. My choice is to use the AutoResetEvent in combination with a WaitHandle. More information on the topic can be found here


No comments:

Post a Comment