How to do it...

  1. Create a new method called MultipleThreadWait() in your Demo class. Then, create a second method called RunThread() with the private modifier that takes an integer of seconds to make the thread sleep. This will simulate the process of doing some work for a variable amount of time:
        public class Demo 
{
public void MultipleThreadWait()
{

}

private void RunThread(int sleepSeconds)
{

}
}
In reality, you would probably not call the same method. You could, for all intents and purposes, call three separate methods. Here, however, for simplicity's sake, we will call the same method with different sleep durations.
  1. Add the following code to your MultipleThreadWait() method. You will notice that we are creating three tasks that then create three threads. We then fire off these three threads and make them sleep for 3, 5, and 2 seconds. Finally, we call the Task.WaitAll method to wait before continuing the execution of the application:
        Task thread1 = Task.Factory.StartNew(() => RunThread(3)); 
Task thread2 = Task.Factory.StartNew(() => RunThread(5));
Task thread3 = Task.Factory.StartNew(() => RunThread(2));

Task.WaitAll(thread1, thread2, thread3);
WriteLine("All tasks completed");
  1. Then, in the RunThread() method, we read the current thread ID and then make the thread sleep for the amount of milliseconds supplied. This is just the integer value for the seconds multiplied by 1000:
        int thread
ID = Thread.CurrentThread.ManagedThreadId;

WriteLine($"Sleep thread {threadID} for {sleepSeconds}
seconds at {DateTime.Now.Second} seconds");
Thread.Sleep(sleepSeconds * 1000);
WriteLine($"Wake thread {threadID} at {DateTime.Now.Second}
seconds");
  1. When you have completed the code, your Demo class should look like this:
        public class Demo 
{
public void MultipleThreadWait()
{
Task thread1 = Task.Factory.StartNew(() => RunThread(3));
Task thread2 = Task.Factory.StartNew(() => RunThread(5));
Task thread3 = Task.Factory.StartNew(() => RunThread(2));

Task.WaitAll(thread1, thread2, thread3);
WriteLine("All tasks completed");
}

private void RunThread(int sleepSeconds)
{
int threadID = Thread.CurrentThread.ManagedThreadId;
WriteLine($"Sleep thread {threadID} for {sleepSeconds}
seconds at {DateTime.Now.Second} seconds");
Thread.Sleep(sleepSeconds * 1000);
WriteLine($"Wake thread {threadID} at {DateTime.Now.Second}
seconds");
}
}
  1. Finally, add a new instance of the Demo class to your console application and call the MultipleThreadWait() method:
        Demo oRecipe = new Demo(); 
oRecipe.MultipleThreadWait();
Console.ReadLine();
  1. Run your console application and view the output produced:
..................Content has been hidden....................

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