Quantcast
Channel: Towards Next » C# 4.0
Viewing all articles
Browse latest Browse all 2

Parallel Programming Framework 4.0 Part 3 – ParallelLoopSate

0
0

Control over program execution is very important. These things we are listening and learning from the time we started with programing. We used to control the execution with the help of If else, Switch, loops. In the case of loops we used to break the execution of the loop with the help of break keyword.

But in case of Parallel programming things are bit different. We can’t use break in Parallel.For or Parallel.ForEach. Solution for this problem is using ParallelLoopState Class. The instance of this class is provided within the body of the loop by Parallel class itself.

Have a look to the following example



class Program·
{
static void Main(string[] args)
{
long size = 0;

string[] urls = { 
"http://towardsnext.wordpress.com",                                  
"http://yahoo.com",                                  
"http://microsoft.com",                                  
"http://google.com",                                 
"http://aol.com",                                 
"http://rediff.com"                              
};

Parallel.ForEach(urls, (url, parallelLoopState, index) =>
{

if (size > 100000)
{
                    parallelLoopState.Stop();·
Console.WriteLine("Breaking Thread, Index Cancelled : " + index.ToString());
}
else

WebClient client = new WebClient();·
Console.WriteLine("Element Index : {1} Downloading : {0} ", url, index);
                    size += client.DownloadString(url).Length;·

Console.WriteLine("Total Size downloaded till now: " + size);
}
});

Console.ReadLine();
}

In this example we are having three parameter url, parallelLoopState and index



url is a data we passed to this body delegate

parallelLoopSate is the instance of the ParallelLoopState class provided by the Parallel Class 

index of the element of that datasource on which we are running are parallel for each. It tell on which element of the source this current body loop is working on

In the above sample we are checking about the size of the content downloaded till now, if it is going beyond 100000 bytes we are telling to the loop to stop iterating further. We achieved this by using parallelLoopState.Stop() function. There is another function available to perform the same task parallelLoopState.Break().

Yes you are right there is a difference between parallelLoopState.Stop() and parallelLoopState.Break(). in case parallelLoopState.Break we use it typically where data source is ordered and if we call break in the loop on 5th element then all the element further to that will not be executed but below and upto 5th element (means 0-4) will be executed, where as in case of parallelLoopState.Stop it will let no other iteration further.



Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images