0
点赞
收藏
分享

微信扫一扫

遥感分类产品精度验证之TIF验证TIF

booksmg2014 2024-07-24 阅读 29

在C#中实现多线程并行计算可以通过使用 Task 和 Parallel 类来实现。这里给出两个简单的示例,一个是使用 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 库自动管理任务的分配和执行。

注意事项

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

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

举报

相关推荐

0 条评论