Sometimes, we need to create multiple threads. Before we can continue, however, we need to wait for these threads to complete doing whatever they need to do. For this, the use of tasks is best suited.
Make sure that you have added the using System.Threading.Tasks;
statement to the top of your Recipes
class.
MultipleThreadWait()
in your Recipes
class. Then, create a second method called RunThread()
with the private
modifier, which 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 Recipes { public void MultipleThreadWait() { } private void RunThread(int sleepSeconds) { } }
MultipleThreadWait()
method. You will notice that we are creating three tasks that then create three threads. We will then fire off these three threads and make them sleep for 3
, 5
, and 2
seconds. Finally, we will 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");
RunThread()
method, we will 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 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");
Recipes
class should look like this:public class Recipes { 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"); } }
Recipe
class to your console application and call the MultipleThreadWait()
method:Chapter7.Recipes oRecipe = new Chapter7.Recipes(); oRecipe.MultipleThreadWait(); Console.ReadLine();