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

相关推荐
程序炼丹师10 分钟前
CMakeLists中 get_filename_component详解
开发语言
꧁Q༒ོγ꧂33 分钟前
C++ 入门完全指南(四)--函数与模块化编程
开发语言·c++
listhi5201 小时前
对LeNet-5的matlab实现,识别MINST手写数字集
开发语言·matlab
qq_433554541 小时前
C++ manacher(求解回文串问题)
开发语言·c++·算法
csbysj20201 小时前
Chart.js 饼图:全面解析与实例教程
开发语言
浩瀚地学1 小时前
【Java】常用API(二)
java·开发语言·经验分享·笔记·学习
程序员小寒1 小时前
从一道前端面试题,谈 JS 对象存储特点和运算符执行顺序
开发语言·前端·javascript·面试
七夜zippoe1 小时前
事件驱动架构:构建高并发松耦合系统的Python实战
开发语言·python·架构·eda·事件驱动
古城小栈1 小时前
Rust Trait 敲黑板
开发语言·rust
FL171713142 小时前
MATLAB的Sensitivity Analyzer
开发语言·matlab