In C#, threads can be created and started by using the Thread class from the System.Threading namespace. You can create a new thread, define the method to execute on that thread, and then start it.
Example: Creating and Starting a Thread
using System;
using System.Threading;
class MyProgram
{
// This method will be executed by the new thread
static void PrintTwoTable()
{
for (int i = 2; i <= 20; i+=2)
{
Console.WriteLine($"Number: {i}");
Thread.Sleep(500); // Sleep for 500 milliseconds to simulate work
}
}
static void Main()
{
// Create a new thread and specify the method to run
Thread thread = new Thread(PrintTwoTable);
// Start the thread
thread.Start();
// Main thread can continue to execute other code
Console.WriteLine("Main thread continues executing...");
thread.Join(); // This blocks the main thread until the created thread finishes
Console.WriteLine("Main thread has finished execution.");
}
}
Output:
Number: 2
Number: 4
Number: 6
Number: 8
Number: 10
Number: 12
Number: 14
Number: 16
Number: 18
Number: 20
Main thread has finished execution.
Explanation:
1. Creating a Thread: A new Thread object is created, passing the method (PrintTwoTable) that should be executed on that thread.
Thread thread = new Thread(PrintTwoTable);
2. Starting the Thread: The Start() method is called on the Thread object, which initiates the execution of the specified method (PrintTwoTable) on a new thread.
thread.Start();
3. Main Thread Execution: While the new thread is running, the main thread can continue to execute other instructions, such as printing messages to the console.
Console.WriteLine("Main thread continues executing...");
4. Waiting for the Thread to Finish: The Join() method is called to block the main thread until the new thread finishes executing. Without this, the main thread might finish its execution (and potentially terminate the application) before the new thread completes.
thread.Join();
C# Create Thread – Interview Questions
Q 1: How to create a thread in C#?
Ans: Using Thread class.
Q 2: Which method starts a thread?
Ans: Start().
Q 3: Can thread execute a method?
Ans: Yes.
Q 4: Can parameters be passed to thread?
Ans: Yes.
Q 5: Can a thread be stopped?
Ans: Yes, but Abort() is not recommended.
C# Create Thread – Objective Questions (MCQs)
Q1. Which class is used to create a thread in C#?
Q2. Which of the following is the correct way to start a thread in C#?
Q3. What delegate is typically used to define a thread method?
Q4. What happens if you call Start() twice on the same thread object?
Q5. How can you determine if a thread is still running?