C# Thread Example
In C#, a thread is an independent path of execution within a program. Each thread can execute different parts of the program code simultaneously. In this tutorial, we'll discuss how to create and use threads in C#.
Syntax
The syntax for creating a new thread in C# is as follows:
Thread t = new Thread(ThreadMethod);
t.Start();
Here, "ThreadMethod" is the method that will be executed on the new thread. The Start method is used to start executing the method on the new thread.
Example
Let's say we want to create a new thread that prints out numbers from 1 to 10. Here's how we can implement it:
using System.Threading;
class Program {
static void Main() {
Thread t = new Thread(PrintNumbers);
t.Start();
for (int i = 1; i <= 10; i++) {
Console.Write(i + " ");
}
}
static void PrintNumbers() {
for (int i = 1; i <= 10; i++) {
Console.Write(i + " ");
}
}
}
Now, we can run the program and see that the numbers are printed out on two different lines, one line from the main thread and the other from the new thread:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Output
When we run the example code above, the output will be:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
This is because the program creates a new thread and prints out the numbers from 1 to 10 on that thread, while simultaneously printing out the same numbers on the main thread.
Explanation
In the example above, we created a new thread that prints out numbers from 1 to 10, while simultaneously printing out the same numbers on the main thread.
We first created a new thread using the Thread class and passed in the method "PrintNumbers" that we want to execute on the new thread. We then started the new thread using the Start method.
In the Main method, we printed out the numbers from 1 to 10 on the main thread using a for loop.
Use
Threads are useful for executing multiple parts of a program code simultaneously, improving the efficiency of your application. You can use threads to perform computationally intensive tasks in the background, while keeping the main thread responsive to user interactions.
Important Points
- When creating a new thread, make sure to start it using the Start method.
- Make sure that your code is thread-safe.
- Be aware of thread synchronization issues when accessing shared resources.
- Always close worker (background) threads before your application exits.
Summary
In this tutorial, we discussed how to create and use threads in C#. We covered the syntax, example, output, explanation, use, and important points of threads in C#. With this knowledge, you can now use threads in your C# code to execute different parts of a program code simultaneously, and improve the efficiency of your application.