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#中如何利用多线程进行并行计算,可以根据具体需求和任务复杂性进行进一步的扩展和优化。

相关推荐
心平气和量大福大27 分钟前
C#-WPF-Window主窗体
开发语言·c#·wpf
白露与泡影1 小时前
Arthas 实战指南:从方法耗时定位到 JVM 变量热修改
服务器·jvm·c#
从零开始的代码生活_2 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
云小逸2 小时前
【C++ 第七阶段:模板、泛型编程与工程综合详解】
开发语言·c++
GIS阵地3 小时前
QgsSingleBandPseudoColorRenderer 完整详解(QGIS 3.40.13 C++)
开发语言·前端·c++·qt·qgis
yaoxin5211233 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python
groundhappy3 小时前
idalib安装和codex ida-mcp配置
linux·开发语言·python
小钻风33664 小时前
Spring Boot 文件上传详解:深入理解 MultipartFile 的使用与原理
java·开发语言
qq_452396235 小时前
第二篇:《Go 开发环境搭建:SDK、IDE、Module 与 Hello World》
开发语言·ide·golang
EIP低代码平台5 小时前
EIP低代码平台系统-字典功能讲解
低代码·c#·工作流