Chapter 2: Threading Classes
The Thread Class:
Once you’ve decided what work needs to be done in a separate thread by your application, you need to create an object of the Thread class.
The Thread class is used for creating threads, controlling them, and for terminating them. I’ll show you how to use this class for creating a thread after we discuss the ThreadStart delegate.
As mentioned in Chapter 1, every piece of code that executes within your application does so within the context of a thread. If you don’t create multiple threads from your code, then your entire code runs within a single thread (usually – the exceptions are the cases where you might call functions within the .NET or other libraries which then create their own threads). We’ll write a simple application that prints out information regarding the thread that is currently executing.
Start Visual Studio, and create a new Console Application. Within the main function, add the following lines:
Thread thisThread = Thread.CurrentThread;
Console.WriteLine("The ID of the current thread is : " + thisThread.ManagedThreadId);
Console.WriteLine("The State of the current thread is : " + thisThread.ThreadState.ToString());
Console.WriteLine("Is this thread a background thread? : " + thisThread.IsBackground.ToString());
You will need to add a
using System.Threading;
statement in order for the code to compile correctly. Most of the Threading related classes appear within this namespace.
Compile and run the project, you should obtain output similar to the following:
The Thread ID of the currently running thread is 1. This is expected, since you only have one thread in your application – the default thread. You also see that the state of the currently running thread is “Running”. At any point of time, a thread can be in one of the following states:
- StopRequested – someone has requested that this thread be stopped.
SuspendRequested – someone has requested that this thread be paused (suspended).
- Running
- Background – this thread is a background thread. Background threads are threads that do not prevent a process from terminating. A process will keep on running until all Foreground threads have completed.
Unstarted
- Stopped
WaitSleepJoin – this thread is currently waiting for another thread to complete.
- Suspended
AbortRequested – someone has requested this thread to be terminated (aborted).
- Aborted
Thread thisThread = Thread.CurrentThread;
The Thread class exposes a static variable called CurrentThread. You can always use this variable to obtain the thread object that represents the currently running thread.
Let’s now see how we can create a new thread.
Attachments
Project Files C# Threading Samples