I am here again to continue the discussion of Threading. Today we will explain how to create threads and related concepts.
In case you haven’t had a look at our previous articles, you can go through the following article series:
Threads can be created in several ways. Let’s go through them one by one in the following.
- Using only with Thread class
This is the simplest way to create threads, it doesn’t use any delegate and simply keep reference to the method it must call.
- Thread t1 = new Thread(PrintMe1);
- t1.Start();
-
- static void PrintMe1()
- {
- Console.WriteLine("I am created using Thread Class");
- }
Output
- Using ThreadStart delegate
The ThreadStart delegate works similar to Step 1 above. It enables starting a thread without passing any argument to the target method.
- Thread t2 = new Thread(new ThreadStart(PrintMe2));
- t2.Start();
-
- static void PrintMe2()
- {
- Console.WriteLine("I am created using ThreadStart delegate");
- }
Output
- Using ParameterizedThreadStart delegate
The ParameterizedThreadStart delegate starts a thread by passing an argument (of any type) to the target method. The argument should be declared as an object type in the target method.
- Thread t3 = new Thread(new ParameterizedThreadStart(PrintMeWithParam));
- t3.Start("ParameterizedThreadStart delegate");
-
- static void PrintMeWithParam(object param)
- {
- Console.WriteLine("I am created using {0}", param);
- }
Output
- Using anonymous delegate
An Anonymous delegate can be used to invoke a thread. The following example also passes the parameter to the target method.
- Thread t4 = new Thread(delegate()
- {
- PrintMeWithParam("anonymous delegate");
- });
- t4.Start();
Output
- Using lambda expression
Lambda expressions can also be used to start a thread. The following example shows how to pass a parameter as well to the target method.
- Thread t5 = new Thread(() => PrintMeWithParam("lambda expression"));
-
- t5.Start();
Output
Join Method
The Join method causes a wait for a thread to finish. In a multi-threading scenario, it can be used to provide blocking functionality by allowing waits for the specified thread.
Let’s first understand the problem without using Join.
- Thread t1 = new Thread(PrintMe);
- t1.Name = "Thread-1";
- t1.Start();
-
- Thread t2 = new Thread(PrintMe);
- t2.Name = "Thread-2";
- t2.Start();
Output
Here you can see that Thread-1 and Thread-2 are competing with each other to execute.
Now let’s run the same code with the join method as in the following snippet.
- Thread t1 = new Thread(PrintMe);
- t1.Name = "Thread-1";
- t1.Start();
- t1.Join();
-
- Thread t2 = new Thread(PrintMe);
- t2.Name = "Thread-2";
- t2.Start();
Output
Now you can see that Thread-2 executes only when Thread-1 finishes or ends the execution.
I hope you have liked the article, please share your comments/suggestions in the comments section.