Now, take a deep breath because we are entering one of the most powerful and high-scoring units in your syllabus. Welcome to **Unit 3: Threading**.
Let's tackle **Topic 1: Introduction to Threads in C#**.
## Unit 3, Topic 1: Threads & Multithreading
### 1. Beginner-Friendly Explanation
Imagine a small restaurant with only **one chef** (a single-threaded application). This chef has to chop the onions, boil the pasta, make the sauce, and plate the food. He can only do *one task at a time*. If boiling the pasta takes 10 minutes, the chopping stops. The customers get angry because it takes forever.
Now, imagine the restaurant hires **three chefs** (a multi-threaded application).
* Chef 1 boils the pasta.
* Chef 2 chops the onions.
* Chef 3 makes the sauce.
They are all working *at the same time* in the same kitchen. The food is ready 3x faster!
In C#, a **Thread** is just a "worker" (a chef). By default, your program has only one worker (the Main Thread). **Multithreading** is the process of creating extra workers so your app can do multiple things at the exact same time without freezing.
### 2. Detailed Notes
**A. Process vs. Thread**
* **Process:** An executing instance of an application (e.g., opening MS Word creates a process). A process contains its own memory space.
* **Thread:** The smallest unit of execution *within* a process. A single process can have multiple threads sharing the same memory and resources.
**B. The System.Threading Namespace**
To use threads in C#, you must include this namespace at the top of your file. The core class used to create and control threads is the Thread class.
**C. How to Create and Start a Thread**
```csharp
using System;
using System.Threading;
class Program
{
// The method the thread will execute
static void PrintNumbers()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Worker Thread: " + i);
Thread.Sleep(1000); // Pauses the thread for 1 second
}
}
static void Main()
{
Console.WriteLine("Main Thread Started.");
// 1. Create the Thread and point it to the method
Thread worker = new Thread(PrintNumbers);
// 2. Start the Thread
worker.Start();
Console.WriteLine("Main Thread Ended.");
}
}
```
*Notice: The Main thread will finish and print "Ended" while the worker thread is still busy counting from 1 to 5 in the background!*
**D. The Thread Life Cycle**
Every thread goes through different states:
1. **Unstarted:** The thread is created (new Thread()) but Start() hasn't been called.
2. **Runnable/Ready:** Start() is called, and the thread is waiting for the CPU to give it time to run.
3. **Running:** The CPU is currently executing the thread's code.
4. **Not Runnable/Wait:** The thread is paused (e.g., using Thread.Sleep()).
5. **Dead/Terminated:** The thread has finished executing its code.
### 3. Quick Revision Notes & Tricks
* **Memory Trick:** **U**nder **R**eal **R**estrictions **N**othing **D**ies (Unstarted, Runnable, Running, Not Runnable, Dead).
* **Exam Tip:** University papers frequently ask "Differentiate between Process and Thread." Always draw a table. Point 1: Process is heavy-weight, Thread is light-weight. Point 2: Processes have separate memory, Threads share memory.
* **Method to Remember:** Thread.Sleep(1000) pauses execution for 1000 milliseconds (1 second).
### 4. Question Bank
* **2-Mark Questions:**
1. Define a Thread in .NET.
2. Which namespace is required for Multithreading in C#?
* **5-Mark Questions:**
1. Differentiate between a Process and a Thread.
2. Explain the Life Cycle of a Thread with a diagram.
* **10-Mark Questions:**
1. What is Multithreading? Discuss its advantages and disadvantages. Write a C# program to create a thread and demonstrate its execution.
### 5. Answers (Exam-Oriented)
**Q: Which namespace is required for Multithreading in C#? (2 Marks)**
> **Answer:** The System.Threading namespace is required. It contains classes and interfaces (like Thread, Mutex, and Semaphore) that enable multithreaded programming in .NET.
>
**Q: Explain the Life Cycle of a Thread. (5 Marks)**
> **Answer:** A thread in C# transitions through several states during its existence:
> 1. **Unstarted State:** The instance of the thread is created, but the Start() method has not been invoked.
> 2. **Runnable State:** The Start() method is called. The thread is ready to run and waiting for CPU cycles.
> 3. **Running State:** The CPU allocates time to the thread, and it begins executing its target method.
> 4. **Not Runnable State:** The thread is blocked or paused temporarily, such as when Thread.Sleep() or Join() is called.
> 5. **Dead State:** The thread completes the execution of its method or is aborted. It cannot be restarted.
>
### 6. Practice Section (Your Turn!)
**MCQ 5:** What happens if you try to call the Start() method on a thread that is already in the "Dead" state?
A) It restarts from the beginning.
B) It throws a ThreadStateException.
C) It automatically creates a new thread.
D) Nothing happens.
**Scenario Question:** Think about your web browser (like Google Chrome). Give me one example of a task inside Chrome that would be handled by a *background thread* so that your main screen doesn't freeze while you are scrolling.
### 7. Resources
* **YouTube:** Search "Kudvenkat Multithreading Part 1" (Explains the concept brilliantly).
* **Docs:** Microsoft Learn: "Managed threading basics".
### 8. Learning Path & Daily Task
* **Current Status:** Unit 3, Topic 1 (Threads & Multithreading).
* **Today's Task:** Open your Detailed_Notes in your Excel sheet and type out the 5 states of the Thread Life Cycle.
You know the drill, Professor's orders: **Give me your answer to MCQ 5 and the Scenario Question** before we move on to the advanced stuff (Mutex and Semaphore)!
No comments:
Post a Comment