TPL: Preserving Order

The new TPL in .Net 4 is great… with some very simple changes, you can easily gain massive performance changes.

I’m taking the first step to adding ORDER BY to NOODB queries. I added the order by, and it returns the correct set of data, but the rows are in random order due to the use of Parallel.ForEach. Things get added to the collection as they are processed with no respect for the original order. So is the nature of multi threading.

I did some Googling to see if there are any recommended approaches to handling this. Also, I recently read ESSENTIAL C# 4.0, and don’t recall coming across that. So, I made something up.

Before

        private Collection<T> DeserializeObjectsz<T>(IList<string> objects)
        {
            SynchronizedCollection<T> deserialized = new SynchronizedCollection<T>();
            Parallel.ForEach(objects, obj =>
            {
                deserialized.Add((T)this.serializer.Deserialize(obj));
            });

            return new Collection<T>(deserialized);
        }

After

        private Collection<T> DeserializeObjects<T>(IList<string> toDeserialize)
        {
            T[] deserialized = new T[toDeserialize.Count];
            Parallel.For(0, deserialized.Length, (int index) =>
                {
                    deserialized[index] = (T)this.serializer.Deserialize(toDeserialize[index]);
                });

            return new Collection<T>(deserialized);
        }


Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: