11
Jan

C# Asynchronous Loops Using Parallel Class Complete Guide


Hello and welcome to one of my C#
lessons. Our lesson today will be about parallel
loops. Here is a content of my lesson today. I
will describe the difference between the standard and parallel loops. Then, I will
show you the for loop with an example in both standard syntax and parallel
syntax. Then, I will show you the same with foreach loop. After that, I will
show you how to break parallel for loops. Finally, I will show you how to use the
result value of parallel for loops. Let’s first understand the difference between standard for loops and parallel loops. The standard for loops are built-in
statements in the C# language. While the parallel loops are created by
a dot NET class defined in System.Threading namespace the standard for loops run sequentially while parallel for loops runs in parallel the standard
for loops run on the same thread while pirelli loops runs under multiple
threads each loop will be running on its own thread the standard for loops have C
sharp break statement to stop the loop while parent loops have two different
methods to stop the loops barrel each class is defined in system dot threading
namespace that can use the to create loops that runs in parallel these loops
can replace a built in for and for each loop since Esha the normal belt in loops
run sequentially however the loops created by parallel
class runs in parallel which means that multiply trations can run at the same
time in multiple threads this process can increase the performance of your
application greatly in some situations generally when the alterations do not
depend on each other and execute code that takes a considerable long time then
using parallel class can enhance the performance of your application the best
way to tell if you really need the parallel loop at the note the standard
loop is to measure the performance of your application with and without using
separate class and decide yourself let’s see the syntax of writing loops you
the perineal class I would first write a normal for loops with the standard
c-sharp Centex then I will convert it to a parallel for loop I will type 4 with a
variable named in and 10 million iterations to write the same loop using
the parallel class I will type parallel dot 4 and note here that for is written
with a capital F the first parameter of this method is starting value which is 0
in our case the second parameter is the loop iteration
Indian condition which is 10 million here note that the first parameter is
inclusive which means that in in the first iteration will be 0 while the
second parameter is exclusive which means that the last iteration n will be
1 less than 10 menu so this loop will execute for n values from 0 to 9 million 999,999 the third parameter here is an
action type which can be written as lambda expression containing the loop
body I will type in equals greeters n then the code braces now we have two
identical loops the only difference is the alterations of the first loop will
run sequentially while the iterations of the second loop will run in parallel in
multiple threads at the same time I will write a statement here to convert the n
value to strength strength converted equals n dot to strength I will copies
same line to the second loop here to measure the time consumed by both loops
in order to be able to compare the performance I will use the stopwatch
class which is defined in the system dot Diagnostics namespace I will define an
object here stopwatch it’s W equals new stopwatch before the first for loop I
will start the stopwatch by typing SW dot start after the loop I will type
console dot write line standard for loop takes and the stopwatch object elapsed
it mainly seconds before the second for loop I will restart the stopwatch SW dot
restart and again after the loop I will type console dot write line parallel for
loop takes and again as W dot elapses milliseconds let’s run the application
now you see the results here there is a big difference in execution time between
both loops the standard loop took about double the time the parallel loop to
execute we are doing a simple task here and the barrel loop was much better but
when it comes to actual longer and more complicated code being executed you may
find the parallel loop executes faster or slower than the standard for loops
according to the code being executed you can judge it and select the suitable
loop according to the situation okay let’s see the for each loop I will
create an array of strings here that holds some website URLs I will I tread
through this array as a collection using both the standard for each imperil
for each loops I will start by array declaration string array URL equals and
between the prices I will initialize this array with some URLs like ee ee ee
dot google.com microsoft.com Visual Studio com you amazon.com youtube.com facebook.com you and finally twitter.com I will create a standard for each loop
for each strengths URL in URLs then the braces I will create the second loop
parallel dot for each and note again that F is capital here then I will pass
the array as the first parameter to this method and the second parameter is my
action the lambda expression URL equals greater than then good braces before
each loop I will restart the stopwatch SW dot restart and here also SW dot
restart after each loop I will print the elapsed time console dot write line
standard for each loop takes s/w dot elapses milliseconds milliseconds here also I will print console dot write
line parallel for each Lu
eggs s/w dot elapses mainly seconds
milliseconds inside the for-loop I will download the home page HTML for each of
these websites I will type here HTTP web request my request equals HTTP web
request web request dot create URL then my request dot method equals get
then with response my response equals my request dot get response then streamreader is our equals new stream
leader my response dot get response three comma including utf-8 here I will get the result string result
equals s r dot read – int then I will close the stream as r dot close and
close the response my response dot close I can type the results but since the
HTML page will be very lengthy I will just type the first thing characters of
the result to the console console dot write line result dot substring of 0 and
10 now this code is ready it will simply download the webpage and then print the
first thing characters of the HTML page I will simply copy this code to the
other loop now let’s run the application you we can see the difference here in the
favor of the parallel for each loop against the standard loop however the
results may not be fair enough since my computer or nearby servers may
be caching the websites from the first request in the for each loop and when
calling again using is apparently loops it may be coming faster from this cache
so we can interchange the code blocks of the loops here and run the application
again you okay the application now will give you
different results and if you run each time you may get different results
according to the situation you can increase the list of websites to get
more accurate results generally as stated earlier in actual situations you
should check the performance and select the better solution okay now let’s talk
about something else here the braking mechanism in the standard four loop the
break statement is used to stop processing of the standard for and for
each loop in C sharp when using parallel loops a similar mechanism exists through
the parallel loop State class if I need to stop the first loop for example in
the counter variable reaches five I can type in the standard for loop F n double
equals five and break statement to do the same in the parallel loop I need to
first replace the standard action that takes only one parameter with another
action that takes two parameters integer type and parallel loop state type so I
will change the definition of the action in the lambda expression to be n comma
State inside the loop I can type F N double equals 5 then call the break
method of the state object I can do the same with for each loops with suitable
conditions let’s run the application now to see the results you great it worked fine you should
understand that since the parallel for and for each loops runs in parallel some
iterations may be executing when you execute the break method break method
when issued will make sure that no additional loops will be created however
it will allow all iterations that are currently running to complete its job
till the end there is another method of the parallel loop state class called
stop this method will stop all loops from running even if their work was not
completed yet we can replace the break method with the stop method heal and run
again this time although the processing is still done in parallel but when the
stop method reaches all current running loops will stop immediately both
parallel for and for each loops return a value of five parallel loop result it is
a struct datatype having two important properties we can make use of when
breaking loops is completed property which indicates if the loop runs till
int including all iterations or it was exited before completion using break or
stop methods the second property is lowest break iteration which indicates
the number of iterations completed by the for or for each loop before breaking
this property is available only when the break method is used it will have a null
value if all iterations completed or if we use the stop method let’s try them
first I will change the call line of the parallel for loop to keep the return
value in a variable so here I will write parallel loop result for reserved equals
and keep the remaining of the line you can use the same syntax for parallel for
each loop now we have a variable containing the return value of
the parallel for method let’s try printing the properties values of this
return value here I will type console dot write line for result dot is
completed then console dot write line for result dot lowest break Idris I will run the application now and see
the results you can see here that the completed property is false since I am
using a stop method here and the lowest break hydration is null because I am
using a stop if I change it the stock method to break I can see the results here is completed
as a still Falls as not all iterations completed and lowest break iteration is
showing the number of completed iterations here if I removed the break
statement I can see the results here again it’s
completed is true because this time I have not stopped the alterations at all
and lowest break iteration is null since I have not used the break method I think
the concept is clear now you can find the final project in the folder panel it
looks inside my previous three named c-sharp lessons in my account on github
as the full address is displayed here github.com slash we have Zacky / c-sharp
lessons / 3 / master / parallel loops thanks a lot for watching this video and
I hope it was beneficial to you if you want me to create other videos please
leave a comment and I will try to create videos on concepts with high demand
thank you and goodbye

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , ,

There are no comments yet

Why not be the first

Leave a Reply

Your email address will not be published. Required fields are marked *