Ticker

6/recent/ticker-posts

Multithreading in C#

Multithreading in C#


Multithreading in C# allows you to execute multiple threads concurrently within a single program, enabling efficient utilization of system resources and improved responsiveness. Each thread represents an independent flow of execution, allowing different parts of your program to run concurrently.

Here's an example that demonstrates multithreading in C#:

c#
using System; using System.Threading; class Program { static void Main() { // Create two threads and assign methods to execute concurrently Thread t1 = new Thread(FirstMethod); Thread t2 = new Thread(SecondMethod); // Start the threads t1.Start(); t2.Start(); // Wait for both threads to finish t1.Join(); t2.Join(); Console.WriteLine("Program completed."); } static void FirstMethod() { for (int i = 0; i < 5; i++) { Console.WriteLine("FirstMethod: " + i); Thread.Sleep(1000); // Pause the thread for 1 second } } static void SecondMethod() { for (int i = 0; i < 5; i++) { Console.WriteLine("SecondMethod: " + i); Thread.Sleep(1000); // Pause the thread for 1 second } } }

In the above example, we create two threads (t1 and t2) and assign different methods (FirstMethod and SecondMethod) to execute concurrently. The Start method is used to start the execution of each thread.

The Join method is then called on each thread to wait for their completion before continuing further. This ensures that the program waits for both threads to finish their execution before printing "Program completed."

Each method represents a separate thread of execution. In this case, both methods simply print numbers in a loop and pause for 1 second using Thread.Sleep. The Thread.Sleep method is used to introduce a delay and simulate some work being done within the threads.

When you run the program, you'll see the output from both methods interleaved, as the two threads execute concurrently. This demonstrates the concurrent execution and interleaving of thread operations.

Multithreading allows you to leverage the power of modern processors with multiple cores and achieve parallelism in your programs. It can be used to perform computationally intensive tasks, handle asynchronous operations, or improve responsiveness in user interfaces.

However, it's important to note that multithreading introduces concurrency and potential synchronization issues. Care must be taken to ensure proper synchronization and coordination between threads to avoid race conditions and other thread-related problems.

Post a Comment

0 Comments