Parallel.Invoke
allows us to execute tasks in (you guessed it) parallel. Sometimes, you need to perform operations simultaneously and, in so doing, speed up processing. You can therefore expect that the total time taken to process the tasks is equal to the longest running process. Using Parallel.Invoke
is quite easy.
Make sure that you have added the using System.Threading.Tasks;
statement to the top of your Recipes
class.
Recipes
class called ParallelInvoke()
and PerformSomeTask()
, which take an integer of seconds to sleep as the parameter:public class Recipes { public void ParallelInvoke() { } private void PerformSomeTask(int sleepSeconds) { } }
ParallelInvoke()
method. This code will call Paralell.Invoke
to run the PerformSomeTask()
method:WriteLine($"Parallel.Invoke started at {DateTime.Now.Second} seconds"); Parallel.Invoke( () => PerformSomeTask(3), () => PerformSomeTask(5), () => PerformSomeTask(2) ); WriteLine($"Parallel.Invoke completed at {DateTime.Now.Second} seconds");
PerformSomeTask()
method, make the thread sleep for the amount of seconds passed to the method as the parameter (converting the seconds to milliseconds by multiplying it by 1000
):int threadID = Thread.CurrentThread.ManagedThreadId; WriteLine($"Sleep thread {threadID} for {sleepSeconds} seconds"); Thread.Sleep(sleepSeconds * 1000); WriteLine($"Thread {threadID} resumed");
Recipes
class should look like this:public class Recipes { public void ParallelInvoke() { WriteLine($"Parallel.Invoke started at {DateTime.Now.Second} seconds"); Parallel.Invoke( () => PerformSomeTask(3), () => PerformSomeTask(5), () => PerformSomeTask(2) ); WriteLine($"Parallel.Invoke completed at {DateTime.Now.Second} seconds"); } private void PerformSomeTask(int sleepSeconds) { int threadID = Thread.CurrentThread.ManagedThreadId; WriteLine($"Sleep thread {threadID} for {sleepSeconds} seconds"); Thread.Sleep(sleepSeconds * 1000); WriteLine($"Thread {threadID} resumed"); } }
Recipes
class and call the ParallelInvoke()
method:Chapter7.Recipes oRecipe = new Chapter7.Recipes(); oRecipe.ParallelInvoke(); Console.ReadLine();
Because we are running all these threads in parallel, we can assume that the longest process will denote the total duration of the all the tasks. This means that the total duration of the process will be 5 seconds because the longest task will take 5 seconds to complete (we set thread 10
to sleep for a maximum of 5 seconds).
As we can see, the time difference between the start and the end of Parallel.Invoke
is exactly 5 seconds.