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) {
} }
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");
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");
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"); }