Parallelism. Using Parallel.For and ConcurrentBag.

Parallelism refers to the technique of running multiple calculations at the same time to speed up a computer program. Historically, this has been a complicated thing to write requiring a developer to do complicated coding including low-level manipulation of threads and locks.

A program will generally run faster if you allow it to execute multiple calculations at the same time. For example, you might have a program where you need check how many orders a customer has, and instead of looping through each customer to check on their orders, you could check on multiple customers at the same time by using something like Parallel.For.

Code example:

private IEnumerable<Orders> MyMethod(List<Orders> orders)
    {
        // Converting the List<Orders> to ConcurrentBag for thread-safe purposes.
        var result = new ConcurrentBag<Orders>();

        Parallel.ForEach(orders, item =>
        {
           // Some data manipulation
           result.Add(new Orders(/* constructor parameters */);
        });

        return result;
    }

The .NET Framework makes writing parallel code a much simpler task than before. A variety of enhancements and additions such as runtime, class library types, and diagnostic tools were introduced with the .NET Framework 4.0 to help developers write safe and efficient parallel code.

Below are some of these tools and enhancements, you can click any of the links for access to Microsoft’s documentation for each one of these:

The benefits

The benefit of using parallel programming is gaining the advantage to execute multiple instructions at the same time. This offers the benefit of making your program faster by reducing the time for the same code to execute sequentially. While this is a great way to speed up your code, you should still consider other ideas as well and not use the framework features around parallelism before knowing more about it. Believe, I know by personal experience, unfortunately.

The disadvantages

The disadvantages of using parallel coding are the increase of use of CPU for it (something to be aware of) and also the potential for issues when using collection objects that aren’t thread-safe. Thread safe means multiple threads can access the common data without any problem. When using something like Parallel.For you want to use a thread-safe object such as ConcurrentBag<T>. Bags are useful for storing objects when ordering doesn’t matter, and unlike sets, bags support duplicates. If you need your collection to be ordered, remember to sort it after converting it to a List<>.

As with everything else, test your code and find out if using the Parallel library or PLINQ in your existing scenario is the right thing for it or not. While it might seem that running things in parallel will always be faster, this isn’t always true. Read more about it here.

Happy coding!

Infinite scroll with ASP.NET MVC

An infinite scroll is a nice solution when you need to display large amounts of content in page, it helps by increasing performance in such a page because only a specific number of items is shown when the page first loads. As the user scrolls down, more content is shown. An infinite scroll is a better solution than having a paginated view of the page which usually breaks the flow of the page by splitting the content into multiple pages and then users have to click on a button or link to be able to see the next group of items…

I’ve used the following infinite scroll solution with ASP.NET MVC sites and it works great and it is simple to implement, all you need is jQuery and a little code in the controller and the view.

First, add a parameter to the controller action that returns the data for your page, this parameter is the one that we’ll use to specify the page number we need to get data for. The real work happens in the GetPaginatedProducts method, every time the user scrolls down the page this method is called by the controller action, we pass the page number and then use the Skip Linq command to get the next set of items.

The Controller

Here is the code we need in the controller for the infinite scroll to work:

controller

The JavaScript

The following is the javascript needed to display a loading image and to initiate the call to the Product action on the HomeController, see below. Also, you will need to create a loading image to display while the application is getting data from the server, I used this site to create mine.

javascript

The View

Finally, in the view we make sure we have at least two divs, one with the id “productList” where the data is appended to when scrolling to the bottom of the page and another one with the id “loading” to use it to display the loading image:

view

Where is the sample project?

I’ve added the sample project to CodePlex, you can download it here: https://github.com/ricardodsanchez/InfiniteScroll

MIX11 – A tribute to Microsoft’s Web Stack of Love!

A few weeks ago I attended MIX11 in Las Vegas. MIX is an annual event where Microsoft showcase their new web technologies. This year it was all about new versions of existing products, such as Windows Phone 7, Entity Framework, Silverlight, ASP.NET MVC, IIS, etc… Below is a summary of what was shared on both keynotes:

  • Mango: code name for coming version of Windows Phone 7 (WP7).
  • ASP.NET MVC 3 Tools update
  • Entity Framework 4.1
  • Silverlight 5 Beta
  • NuGet
  • IIS Express
  • SQL Compact Edition 4
  • Internet Explorer 10 Preview
There were many sessions available, some of them really good and some others were not. One thing that I did appreciate was the endless supply of coffee, water and other drinks. Snacks were available as well between breakfast and lunch which were also provided by Microsoft.
All sessions are now available online as well as both keynotes, check them out!
As a software developer, the most interesting for me was the ASP.NET MVC 3 tools update, EF 4.1. Continue reading →