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.
The parallel class belongs to the System.Threading.Tasks Namespace. With the parallel class we execute any task parallel easily.
List<string> sites = new List<string>
List<PingReply> pingReplies = new List<PingReply>();
System.Threading.Tasks.Parallel.ForEach(sites, site =>
Ping p = new Ping();
foreach (var s in pingReplies.ToList())
Response.Write(s.Address + ": " + s.RoundtripTime + ": " + s.Status + "<br />");
Dim sites As New List(Of String)
Dim pingReplies As New List(Of PingReply)()
Dim p As New Ping()
For Each s In pingReplies.ToList()
Response.Write(Convert.ToString(s.Address) & ": " & Convert.ToString(s.RoundtripTime) & ": " & Convert.ToString(s.Status) & "<br />")
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.