Let us talk about Data Parallelism, which means concurrent opertaion over collections, array etc.
Parallel.For and Parallel.ForEach, These methods are available in the System.Threading.Tasks.Parallel class. While working with Parallel for or Parallel foreach collections or array are partitioned so that multiple threads can work concurrently on it. We will talk about how to use the parallel foreach as well as about other functionality associated with it
To understand more about it, let us look at the example given below. In this example we have to download the webpages content and for this we will use parallel.foreach
using System;
using System.Net;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] urls = { "http://towardsnext.wordpress.com",
"http://yahoo.com",
"http://microsoft.com",
"http://google.com",
"http://aol.com",
"http://rediff.com"
};
Stopwatch stopWatch = new Stopwatch();
//Regular foreach and downloading content
Console.WriteLine("Regular Foreach");
stopWatch.Start();
foreach (string url in urls)
{
WebClient client = new WebClient();
Console.WriteLine("Downloading : " + url);
client.DownloadString(url);
}
Console.WriteLine(stopWatch.ElapsedMilliseconds.ToString());
stopWatch.Stop();
Console.WriteLine("Parallel Foreach");
stopWatch.Restart();
Parallel.ForEach(urls, url =>
{
WebClient client = new WebClient();
Console.WriteLine("Downloading : " + url);
client.DownloadString(url);
});
Console.WriteLine(stopWatch.ElapsedMilliseconds.ToString());
stopWatch.Stop();
Console.ReadLine();
}
}
}
Output :
In this sample program we have used foreach as well as parallel.foreach. In this case Parallel.foreach will be faster since it will instantiate more than one task to download the webpages where as in normal or regular foreach it will be downloading one by one.
