- Author

- Name
- Nelson Silva
- Social
Introduction
Multithreaded programming is a technique that allows the concurrent execution of two or more parts of a program for maximum CPU utilization. In C#, Thread is the base class for creating and working with threads.
Thread Class Features
The Thread class, which is part of the System.Threading namespace, offers a range of functionalities for creating, controlling, and obtaining information about threads:
- Thread Creation: With the
Threadclass, it is possible to start a task in the background. - Control: Allows pausing, resuming, or terminating a thread.
- Information: Provides data about the current state of the thread, such as whether it is running, suspended, terminated, etc.
- Priority: The priority of a thread can be adjusted, which affects the execution order of threads.
Common Methods
Here are some of the most commonly used methods:
Thread.Start()
- Starts the execution of the thread.
Thread.Join()
- Blocks the calling thread until the thread on which it is called finishes its execution. Useful for ensuring that one thread finishes before another begins.
Thread.Sleep(int milliseconds)
- Pauses the running thread for the specified number of milliseconds.
Illustrative Example
The following example illustrates the creation and execution of a thread, as well as the control of the execution flow between two threads.
using System;
using System.Threading;
namespace Examples {
class ThreadDemo {
private Thread newThread;
public void Start() {
newThread = new Thread(SecondaryTask);
newThread.Start();
for (int index = 1; index <= 5; index++) {
Console.WriteLine($"Start() method #{index}");
Thread.Sleep(1000);
}
Console.WriteLine("The Start() task has completed.");
newThread.Join();
Console.WriteLine("The SecondaryTask() task has completed.");
}
private void SecondaryTask() {
for (int index = 1; index <= 10; index++) {
Console.WriteLine($"SecondaryTask() #{index}");
Thread.Sleep(1000);
}
}
}
}
Considerations
When working with multiple threads, it is essential to keep some considerations in mind:
- Deadlocks: Situations in which two or more threads wait indefinitely for each other.
- Race Conditions: When multiple threads try to access and modify a variable at the same time.
- Synchronization: Use of mechanisms such as
lock,Monitor, andMutexto ensure that resources are accessed by one thread at a time.
Conclusion
Multithreaded programming can provide faster and more responsive applications. However, it comes with its own set of challenges. Fortunately, C# offers robust tools, such as the Thread class, to help developers tackle these challenges.