How to do it...

  1. Start off by creating two methods in the Demo class called ParallelInvoke() and PerformSomeTask() that take an integer of seconds to sleep as the parameter:
        public class Demo 
{
public void ParallelInvoke()
{

}

private void PerformSomeTask(int sleepSeconds)
{

}
}
  1. Add the following code to the 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");
  1. In the 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");
  1. When you've added all the code, your Demo class should look like this:
        public class Demo 
{
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");
}
}
  1. In the console application, instantiate a new instance of the Demo class and call the ParallelInvoke() method:
        Demo oRecipe = new Demo(); 
oRecipe.ParallelInvoke();
Console.ReadLine();
  1. Run the console application and look at the output produced in the console window:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.151.220