Correct use of Parallel for loop in C#?

自古美人都是妖i 提交于 2021-01-27 05:50:49

问题


In this example, is this the correct use of the Parallel.For loop if I want to limit the number of threads that can perform the function DoWork to ten at a time? Will other threads be blocked until one of the ten threads becomes available? If not, what is a better multi-threaded solution that would still let me execute that function 6000+ times?

class Program
{
    static void Main(string[] args)
    {
        ThreadExample ex = new ThreadExample(); 
    }
}

public class ThreadExample
{
    int limit = 6411; 

    public ThreadExample()
    {
        Console.WriteLine("Starting threads...");
        int temp = 0; 
        Parallel.For(temp, limit, new ParallelOptions { MaxDegreeOfParallelism = 10 }, i =>
        {
            DoWork(temp);
            temp++; 
        }); 
    }

    public void DoWork(int info)
    {
        //Thread.Sleep(50); //doing some work here. 

        int num = info * 5; 

        Console.WriteLine("Thread: {0}      Result: {1}", info.ToString(), num.ToString());
    }
}

回答1:


You need to use the i passed to the lambda function as index. Parallel.For relieves you from the hassle of working with the loop counter, but you need to use it!

    Parallel.For(0, limit, new ParallelOptions { MaxDegreeOfParallelism = 10 }, i =>
    {
        DoWork(i);
    });

As for your other questions:

  • Yes, this will correctly limit the amount of threads working simultaneously.
  • There are no threads being blocked. The iterations are queued and as soon as a thread becomes available, it takes the next iteration (in a synchronized manner) from the queue to process.


来源:https://stackoverflow.com/questions/14222037/correct-use-of-parallel-for-loop-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!