In this article I will explain with a simple example how to use Parallel ForEach Loop in C# and VB.Net using .Net 4.0 and .Net 4.5.
Parallelism can be achieved in two ways
1.     Parallel class
2.     PLINQ (Parallel LINQ)
Here I will be explaining how to achieve parallelism using Parallel ForEach Loop with an example that will have a list of websites in an string collection and we’ll try to ping the sites in parallel. In the example I’ll be making use of the following namespace to access the Ping class.
C#
using System.Net.NetworkInformation;
 
VB.Net
Imports System.Net.NetworkInformation

 
Parallel class
The parallel class belongs to the System.Threading.Tasks Namespace. With the parallel class we execute any task parallel easily.
C#
List<string> sites = new List<string>
{
"www.yahoo.com",
"www.google.com",
"www.aspsnippets.com"
};
 
List<PingReply> pingReplies = new List<PingReply>();
System.Threading.Tasks.Parallel.ForEach(sites, site =>
{
    Ping p = new Ping();
    lock (pingReplies)
    {
        pingReplies.Add(p.Send(site));
    }
});
 
foreach (var s in pingReplies.ToList())
{
    Response.Write(s.Address + ": " + s.RoundtripTime + ": " + s.Status + "<br />");
}
 
VB.Net
Dim sites As New List(Of String)
sites.Add("www.yahoo.com")
sites.Add("www.google.com")
sites.Add("www.aspsnippets.com")
 
Dim pingReplies As New List(Of PingReply)()
System.Threading.Tasks.Parallel.ForEach(sites, Sub(site)
                                        Dim p As New Ping()
                                        SyncLock pingReplies
                                            pingReplies.Add(p.Send(site))
                                        End SyncLock
                                        End Sub)
 
 
For Each s In pingReplies.ToList()
       Response.Write(Convert.ToString(s.Address) & ": " & Convert.ToString(s.RoundtripTime) & ": " & Convert.ToString(s.Status) & "<br />")
Next

 
In the above example I am pinging the sites in parallel using Parallel Task class. I have also created another collection of Ping Replies and I am adding the ping reply of each site to that collection. You will notice I have put a lock on the collection as this is a parallel operation.
 
Demo
 
Downloads