- What are the reasons to create a dedicated thread?
- What is the Thread.Join() method?
The reasons to create a dedicated thread:
1. We want to set a priority level for a thread. By default the CLR creates threads with the Normal priority if we want to set other levels we need to create a dedicated thread.
2. We need that a thread was the foreground thread so the main thread couldn’t stop running until the foreground thread was running.
3. If a thread needs too much time to perform compute-bound operations.
4. If we need to stop a thread execution using the Thread.Abort() method.
Name | Description | |
Thread(ParameterizedThreadStart) | Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started. | |
Thread(ThreadStart) | Initializes a new instance of the Thread class. | |
Thread(ParameterizedThreadStart, Int32) | Initializes a new instance of the Thread class, specifying a delegate that allows an object to be passed to the thread when the thread is started and specifying the maximum stack size for the thread. | |
Thread(ThreadStart, Int32) | Initializes a new instance |
static void Main(string[] args)
{
ParameterizedThreadStart parameterizedThreadStartDelegate = new ParameterizedThreadStart(DoWork);
Thread thread = new Thread(parameterizedThreadStartDelegate);
thread.Priority = ThreadPriority.Normal;
thread.IsBackground = true;
thread.Start(10000000);
Console.WriteLine(“Now wait till the thread destroy itself”);
thread.Join(1000);
Console.WriteLine(“We’ve done!”);
//Console.ReadKey();
}
public static void DoWork(object data)
{
Console.WriteLine(“Sleep for {0} ms”, data);
for (int i = 0; i < (int)data; i++)
{
Console.WriteLine(i);
}
}
The Thread.Join() methods cause the calling thread to stop executing any code until the dedicated thread has destroyed itself or been terminated.
Join ()()() | Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping. | |
Join(Int32) | Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping. | |
Join(TimeSpan) | Blocks the calling thread until a thread terminates or the specified time elapses, while continuing to perform standard COM and SendMessage pumping. |