How to use Data Parallelism from the Task Parallel Library in C#

I wrote a program a few months back that populated a dropdown list with contents from a class using reflection. I used a normal for each statement.

[sourcecode language="csharp" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
foreach (Type type in assembly.GetTypes()
 .OrderBy(f => f.MetadataToken))
 {
   if (type.Namespace != null)
   {
    if (!type.Namespace.ToLower().StartsWith("namespace"))
      combobox1.Add(new ComboBoxClass(type.Name, type.FullName));
   }
 }
[/sourcecode]

In a meeting, someone commented on the performance of the population of this dropdown list. There was a little lag time, very little but noticeable. I decided that I would try to find a way to make it faster. After some research I decided to use the Data Parallelism capabilities found within the Task Parallel Library which is new in .Net 4.0. After a short time, I was able to come up with this code which does the same things but on a different thread and processes the dropdown list change much faster. At least, there is no longer a lag during the rendering.

[sourcecode language="csharp" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
Parallel.ForEach(assembly.GetTypes()
  .OrderBy(f => f.MetadataToken), item =>
{
  if (item.Namespace != null)
  {
    if (!item.Namespace.ToLower().StartsWith("namespace"))
    combobox1.Add(new ComboBoxClass(item.Name, item.FullName));
  }
});
[/sourcecode]

There are some nice new features in .Net 4.0. As C# programmers, we should always try to push forward the utilization of new technologies. Most of the time new features are either a modification or improvement to something which already exists or a new concept that has been introduced into the industry. Both of which add value to us as programmers when we are aware of them, what these new features are for and how to implement them correctly.



Leave a Comment

Your email address will not be published.