问题描述
在此示例中,如果我想将可以执行函数 DoWork
的线程数限制为 10 处,这是 Parallel.For
循环的正确使用吗?一次?在十个线程之一可用之前,其他线程是否会被阻塞?如果没有,什么是更好的多线程解决方案,它仍然可以让我执行该函数 6000 多次?
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());
}
}
推荐答案
您需要使用传递给 lambda 函数的 i
作为索引.Parallel.For
使您免于使用循环计数器的麻烦,但您需要使用它!
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);
});
至于您的其他问题:
- 是的,这将正确限制同时工作的线程数量.
- 没有线程被阻塞.迭代会排队,一旦有线程可用,它就会从队列中进行下一次迭代(以同步方式)进行处理.
这篇关于在 C# 中正确使用 Parallel for 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!