Welcome to my blog, stay tunned :
Home | Blogs | Stephane Eyskens's blog

Leveraging .NET 4 in SharePoint 2013 Series (5) - .AsParallel()

Hi,

I'll be writing a series of blog posts about leveraging .NET 4 within SharePoint 2013. As you might know already, SharePoint 2013 is now based on this .NET runtime version v4.0.30319 which actually allows developers to benefit from .NET 4 features. You couldn't do that with SharePoint 2010 which was still based on .NET runtime v2.0.50727.

.AsParallel()

Parallel programming can be very useful in some scenarios. However, since the foodprint to create the multiple threads is quite heavy, it is important to use it with caution in order to avoid having counter-performing code. As a rule of thumb, one might consider that it's particularly useful when dealing with heavy operations such as iterating through large collections of objects. or performing very heavy operations such as copying big files etc...

On top of the above considerations, it's only interesting to use parallel programming on a server that has multiple cores available to run your code.

Say that you want to dump all the documents stored in document libraries for all your sites. Depending on the number of sites/documents/cores you have, parallel programming can be very interesting. Consider the following code:

SPWebService.ContentService.WebApplications.AsParallel().ForAll(WebApp =>
{
    WebApp.Sites.AsParallel().ForAll(Site =>
        {
            Site.AllWebs.AsParallel().ForAll(Web=>
                {
                    SPListCollection Lists = Web.GetListsOfType(SPBaseType.DocumentLibrary);
                    foreach (SPList List in Lists)
                    {
                        foreach (SPFile ListFile in List.RootFolder.Files)
                        {

                            using (BinaryWriter bw = new BinaryWriter(
                                File.Open(string.Concat(@"C:\tmp\dump\", Web.ID, "_", ListFile.Name), FileMode.Create)
                                ))
                            {
                                bw.Write(ListFile.OpenBinary());
                            }
                        }
                    }
                    Web.Dispose();
                });
        });
});

Drawbacks

As you can see, once I'm iterating through the webs, I don't use AsParallel() anymore to avoid having concurrent threads accessing objects from the same SPWeb object because at the time of writing this is likely to cause thread-safety issues.

However, the above code is pretty efficient compared to a non-parallel code block for a farm having many site collections/sub sites & documents.

Happy Coding!

Comments

Hello stephane, is there any

Hello stephane,

is there any difference with the Parallel.ForEach you describe in the previous post? (performance or whatever)

Christopher.

Performance

No, there is no real difference but the goal was to show both syntaxes