c#

c#的for循环中如何实现多线程操作

小樊
81
2024-09-10 07:16:23
栏目: 编程语言

在C#中,可以使用Parallel.For或者Task来实现多线程操作。下面是两种方法的示例:

  1. 使用Parallel.For
using System;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        int start = 0;
        int end = 10;

        Parallel.For(start, end, i =>
        {
            Console.WriteLine($"Task {i} is running on thread {Task.CurrentId}");
            // 在这里执行你的任务
        });

        Console.ReadKey();
    }
}
  1. 使用Task
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        int start = 0;
        int end = 10;

        Task[] tasks = new Task[end - start];

        for (int i = start; i < end; i++)
        {
            int index = i; // 避免闭包问题
            tasks[index] = Task.Run(() =>
            {
                Console.WriteLine($"Task {index} is running on thread {Task.CurrentId}");
                // 在这里执行你的任务
            });
        }

        await Task.WhenAll(tasks);

        Console.ReadKey();
    }
}

这两种方法都可以实现在for循环中进行多线程操作。Parallel.For更简洁,但是Task提供了更多的控制和灵活性。请根据你的需求选择合适的方法。

0
看了该问题的人还看了