溫馨提示×

c#的for循環(huán)中如何實現(xiàn)多線程操作

c#
小樊
81
2024-09-10 07:16:23
欄目: 編程語言

在C#中,可以使用Parallel.For或者Task來實現(xiàn)多線程操作。下面是兩種方法的示例:

  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}");
            // 在這里執(zhí)行你的任務
        });

        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}");
                // 在這里執(zhí)行你的任務
            });
        }

        await Task.WhenAll(tasks);

        Console.ReadKey();
    }
}

這兩種方法都可以實現(xiàn)在for循環(huán)中進行多線程操作。Parallel.For更簡潔,但是Task提供了更多的控制和靈活性。請根據(jù)你的需求選擇合適的方法。

0