Multithreading in .NET – Parallel Programming
Multithreaded-parallel programming in .NET
In the .NET framework, multi-threaded programming can improve the performance and concurrency of the program. The .NET framework provides a series of classes and APIs to simplify multi-threaded programming. This article will introduce multithreading in .NET-parallel programming, and give some sample codes.
What is multithreading?
Multithreading refers to the simultaneous execution of multiple threads in a process. Each thread is an independent execution path that can execute different codes at the same time. Multithreaded programming can improve program performance and responsiveness, especially when dealing with large amounts of data or tasks that require long waits.
Multithreading in .NET-parallel programming
In .NET, you can use the classes and APIs in the System.Threading namespace for multi-threaded programming. Here are some commonly used classes and APIs:
- Thread class: represents an execution thread, which can be used to create a new thread and start execution.
- ThreadPool class: represents a thread pool that can be used to manage a group of reusable threads.
- Task class: represents an operation that can be performed asynchronously, and can be used to implement asynchronous programming.
- Parallel class: represents a parallel computing library, which can be used to execute parallel loops, parallel LINQ queries, etc.
Below is some sample code that demonstrates how to use these classes and APIs.
Create a thread using the Thread class
We use the Thread class to manually create and start a thread to achieve simple parallel computing. Here is a sample code:
using System;
using System. Threading;
class Program
{
static void Main()
{
// create a new thread
Thread thread = new Thread(new ThreadStart(DoWork));
// start thread execution
thread. Start();
// Wait for thread execution to complete
thread. Join();
Console.WriteLine("The main thread ends.");
Console. ReadKey();
}
static void DoWork()
{
Console.WriteLine("The child thread starts to execute.");
Thread.Sleep(1000); // Simulate execution for 1 second
Console.WriteLine("The execution of the child thread is completed.");
}
}
This example demonstrates how to use the Thread class to create and start a thread. In the Main method, we first create a Thread object, pass the method DoWork to be executed as a parameter to the Thread constructor, and then call the Thread.Start method to start the thread. The DoWork method will be executed in a new thread, some information will be output during the execution, and then the Thread.Sleep method will be called to simulate the thread to perform operations for 1 second, and finally the thread will end execution.
Use the ThreadPool class to create a thread pool
Use the ThreadPool class to automatically manage the thread pool, execute multiple work items, and realize simple parallel computing. Here is a sample code:
using System;
using System. Threading;
class Program
{
static void Main()
{
// add work item to thread pool
ThreadPool.QueueUserWorkItem(DoWork, "Work Item 1");
ThreadPool.QueueUserWorkItem(DoWork, "Work Item 2");
Console.WriteLine("The main thread ends.");
Console. ReadKey();
}
static void DoWork(object state)
{
Console.WriteLine("The work item starts to execute: " + state);
Thread.Sleep(1000); // Simulate execution for 1 second
Console.WriteLine("Work item execution completed: " + state);
}
}
This example demonstrates how to use the ThreadPool class to execute multiple work items. In the Main method, we first call the ThreadPool.QueueUserWorkItem method, and pass the method DoWork to be executed as a parameter to the method. ThreadPool will automatically manage the threads in the thread pool to execute the DoWork method. The DoWork method will be executed in a new thread, some information will be output during the execution, and then the Thread.Sleep method will be called to simulate the operation of the thread for 1 second, and finally the thread will end its execution.
Use the Task class to implement asynchronous programming
Use the Task class to implement asynchronous programming, so that the CPU can perform other tasks while waiting for the completion of the asynchronous operation, thereby improving the utilization rate of the CPU, and also realizing simple parallel computing to avoid blocking the UI thread. Here is a sample code:
using System;
using System. Threading. Tasks;
class Program
{
static void Main()
{
Console.WriteLine("Start asynchronous operation.");
Task.Run(() => DoWork());
Console.WriteLine("Asynchronous operation started.");
Console. ReadKey();
}
static void DoWork()
{
Console.WriteLine("Asynchronous operation starts.");
Task.Delay(1000).Wait(); // Simulate execution for 1 second
Console.WriteLine("Asynchronous operation completed.");
}
}
This example demonstrates how to use the Task class to implement asynchronous programming. In the Main method, we use the Task.Run method to create an asynchronous operation, Pass the method DoWork to be executed as a parameter to the method. The asynchronous operation will be executed in a new thread, some information will be output during the execution, and then the Task.Delay method will be called to simulate the asynchronous operation for 1 second, and finally the asynchronous operation will be executed.
Use the Parallel class to perform parallel computing
Using the Parallel class to perform parallel calculation and summation on the array, using the computing power of multiple processors, and improving the execution efficiency of the program. Here is a sample code:
using System;
using System. Linq;
using System. Threading. Tasks;
class Program
{
static void Main()
{
int[] data = Enumerable.Range(0, 10000000).ToArray();
// use parallel computing to sum
long sum = 0;
Parallel. ForEach(data, x => { Interlocked. Add(ref sum, x); });
Console.WriteLine("The sum is: " + sum);
Console. ReadKey();
}
}
This example demonstrates how to use the Parallel class to perform parallel computations. In the Main method, we first use the Enumerable.Range method to create an integer array data with a length of 10000000, and then use the Parallel.ForEach method to calculate and sum the array in parallel. The Parallel.ForEach method will automatically divide the array into multiple parts, perform calculation operations in multiple threads, and finally accumulate the results to get the final result.
Summary
In the .NET framework, multi-threaded programming can improve the performance and concurrency of the program. The .NET framework provides a series of classes and APIs to simplify multi-threaded programming. This article introduces the multi-thread-parallel programming in .NET, and gives some sample codes, hoping to help everyone.
References
- Thread Class,
- ThreadPool Class
- Task Class
- Parallel Class
- Summary of concepts related to multithreading