C#多线程并行计算实例

在C#中实现多线程并行计算可以通过使用 TaskParallel 类来实现。这里给出两个简单的示例,一个是使用 Task,另一个是使用 Parallel.ForEach

使用 Task 进行多线程并行计算

复制代码
using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        // Example: Calculating squares of numbers in parallel
        int[] numbers = { 1, 2, 3, 4, 5 };
        Task[] tasks = new Task[numbers.Length];

        for (int i = 0; i < numbers.Length; i++)
        {
            int index = i; // To avoid the modified closure issue
            tasks[i] = Task.Run(() =>
            {
                int result = numbers[index] * numbers[index];
                Console.WriteLine($"Square of {numbers[index]} is {result}");
            });
        }

        Task.WaitAll(tasks); // Wait for all tasks to complete
        Console.WriteLine("All tasks completed.");
    }
}
  • 在上面的例子中,使用 Task.Run() 来启动每个任务,计算数字的平方并输出结果。Task.WaitAll(tasks) 确保所有任务执行完毕后程序继续执行。

使用 Parallel.ForEach 进行多线程并行计算

复制代码
using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        // Example: Calculating squares of numbers in parallel using Parallel.ForEach
        int[] numbers = { 1, 2, 3, 4, 5 };

        Parallel.ForEach(numbers, number =>
        {
            int result = number * number;
            Console.WriteLine($"Square of {number} is {result}");
        });

        Console.WriteLine("All tasks completed.");
    }
}
  • 在这个例子中,使用 Parallel.ForEach 来并行遍历数组 numbers,对每个元素进行平方计算并输出结果。这种方式简化了多线程编程,由 .NET 库自动管理任务的分配和执行。

注意事项

  • 在进行并行计算时,要注意数据的共享和同步问题,确保线程安全性。
  • 使用 TaskParallel 类可以简化多线程编程,同时利用现代多核处理器的能力提升应用程序的性能。

这些示例展示了在C#中如何利用多线程进行并行计算,可以根据具体需求和任务复杂性进行进一步的扩展和优化。

相关推荐
Eiceblue6 分钟前
通过 C# 将 HTML 转换为 RTF 富文本格式
开发语言·c#·html
故渊ZY7 分钟前
Java 代理模式:从原理到实战的全方位解析
java·开发语言·架构
leon_zeng014 分钟前
Qt Modern OpenGL 入门:从零开始绘制彩色图形
开发语言·qt·opengl
会飞的胖达喵15 分钟前
Qt CMake 项目构建配置详解
开发语言·qt
ceclar12317 分钟前
C++范围操作(2)
开发语言·c++
一个尚在学习的计算机小白18 分钟前
java集合
java·开发语言
IUGEI26 分钟前
synchronized的工作机制是怎样的?深入解析synchronized底层原理
java·开发语言·后端·c#
z***I39430 分钟前
Java桌面应用案例
java·开发语言
来来走走1 小时前
Android开发(Kotlin) LiveData的基本了解
android·开发语言·kotlin
明洞日记1 小时前
【数据结构手册002】动态数组vector - 连续内存的艺术与科学
开发语言·数据结构·c++