Sure! I can provide you with an example of using the Join()
method in C# threading.
The Join()
method is used to block the calling thread until a specified thread terminates. It allows you to wait for the completion of a thread before continuing with the execution of the calling thread.
Here’s an example that demonstrates the usage of the Join()
method:
using System; using System.Threading; class Program { static void Main() { Thread thread = new Thread(WorkerThread); thread.Start(); Console.WriteLine("Main thread is doing some work."); // Wait for the worker thread to complete using Join() thread.Join(); Console.WriteLine("Worker thread has completed. Main thread exiting."); } static void WorkerThread() { Console.WriteLine("Worker thread started."); Thread.Sleep(3000); // Simulate some work Console.WriteLine("Worker thread finished."); } }
In this example, we create a new thread called WorkerThread
using the Thread
class. The WorkerThread
method simulates doing some work by sleeping for 3 seconds. Meanwhile, the main thread continues executing and prints “Main thread is doing some work.”
After starting the worker thread with thread.Start()
, we call thread.Join()
to wait for the worker thread to complete. The Join()
method blocks the main thread until the worker thread finishes executing.
Once the worker thread completes its work, it prints “Worker thread finished.” At this point, the main thread can continue executing and prints “Worker thread has completed. Main thread exiting.”
By using the Join()
method, we ensure that the main thread waits for the worker thread to finish its work before continuing further.
I hope this example helps you understand how to use the Join()
method in C# threading! Let me know if you have any further questions.