In this article I will explain what is Parallel LINQ (PLINQ) and a simple example how to write a PLINQ Query in C# and VB.Net .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 LINQ (PLINQ) 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
 
 
PLINQ (Parallel LINQ)
Next technique is very similar to above but belongs to a different namespace i.e. System.Linq
C#
List<string> sites = new List<string>
{
"www.yahoo.com",
"www.google.com",
"www.aspsnippets.com"
};
 
List<PingReply> pingReplies = (from site in sites.AsParallel().WithDegreeOfParallelism(sites.Count)
                           select DoPing(site)).ToList() as List<PingReply>;
 
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 List(Of PingReply) = TryCast((
                  From site In sites.AsParallel().WithDegreeOfParallelism(sites.Count) _
                  Select DoPing(site)).ToList(), List(Of PingReply))
 
For Each s In pingReplies.ToList()
    Response.Write(Convert.ToString(s.Address) & ": " & Convert.ToString(s.RoundtripTime) & ": " & Convert.ToString(s.Status) & "<br />")
Next
 
Above you will notice that I am executing a LINQ query on the List of the sites. It looks like a normal LINQ query the only difference is that I have used the additional methods AsParallel (Tells the compiler to execute query in parallel) and WithDegreeOfParallelism (Allows you to specify the number of threads executed in parallel). Also I am calling a Method DoPing which basically pings the site and returns the Ping Reply, this method is described below
C#
private PingReply DoPing(string site)
{
    Ping p = new Ping();
    return p.Send(site);
}
 
VB.Net
Private Function DoPing(ByVal site As String) As PingReply
    Dim p As New Ping()
    Return p.Send(site)
End Function
 
 
Demo
 
Downloads