Join. In .NET we use methods to perform threading. On the Thread type, we find the Join instance method. It enables us to wait until a thread finishes.
Method use. We use the C# Join method on an array of threads to implement useful threading functionality. Join() can be called on a Thread instance.
This program creates an array of 4 threads and then calls a method on each thread. The method called (Start) requires 10,000 milliseconds to complete because it calls Thread.Sleep.
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main()
{
var stopwatch = Stopwatch.StartNew();
// Create an array of Thread references.
Thread[] array = new Thread[4];
for (int i = 0; i < array.Length; i++)
{
// Start the thread with a ThreadStart.
array[i] = new Thread(new ThreadStart(Start));
array[i].Start();
}
// Join all the threads.
for (int i = 0; i < array.Length; i++)
{
array[i].Join();
}
Console.WriteLine("DONE: {0}", stopwatch.ElapsedMilliseconds);
}
static void Start()
{
// This method takes ten seconds to terminate.
Thread.Sleep(10000);
}
}DONE: 10001
The results show the effectiveness of threading. The four threads would have slept for ten seconds each, but the entire program only took ten seconds total to execute.
ThreadPool. Instead of using a Thread array and implementing the threading functionality, you can use the ThreadPool type. This has further improvements that can improve CPU utilization.
Summary. Join() from the .NET System.Threading namespace is an important C# threading method. It provides blocking functionality that waits for the specified thread to complete.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 24, 2024 (simplify).