限制线程数C#

时间:2017-02-10 13:25:05

标签: c# multithreading

我必须运行一个包含许多交互的循环,所以我想使用线程,但我不知道如何控制线程的数量:

for (int i = 0; i < 45856582; i = i + 10000)
{
    string result = request.Get(String.Format(mold, i));
    Worker temp = new Worker(i, i + 10000);
    Thread th = new Thread( new ThreadStart( temp.DoWork ));
    th.Start();
}

这个循环会创建太多的线程,我怎么能以循环停止的方式创建它并且不会创建比某个数字更多的线程并等待一个创建的线程完成以继续?< / p>

这是工人阶级:

public class Worker
{
    int startIndex = 0;
    int endIndex   = 0;

    public Worker(int startIndex , int endIndex)
    {
        this.startIndex = startIndex;
        this.endIndex   = endIndex;
    }

    public void DoWork()
    {

        for (int i = startIndex; i < endIndex; i++)
        {
            // Do Work
        }
    }
}

2 个答案:

答案 0 :(得分:6)

我建议您更改整个代码以使用Parallel类:

https://msdn.microsoft.com/en-us/library/dd781401(v=vs.110).aspx

// Options to the set maximum number of threads. 
// This is not necessary, .NET will try to use the best amount of cores there is. (as pointed out by Panagiotis Kanavos)
// Overload of method is available without the options parameter
var options = new ParallelOptions()
{
    MaxDegreeOfParallelism = 4 // maximum number of threads
};

const int batchSize = 1000;
int totalSize = 45856582;
int loops = totalSize / batchSize;

// if there is a rest in the division (in this case 582)
// then add an extra loop
if(totalSize % batchSize != 0) 
    loops++;

// The body on the loop
Action<int> loopBody = i =>
{
    Worker temp = new Worker(i * batchSize, i * batchSize + batchSize);
    temp.DoWork();
};

// The result. Check for loopResult.IsCompleted if everything went correctly
var loopResult = Parallel.For(0, loops, options, loopBody);

或者您可以使用该方法的重载来支持取消等。

答案 1 :(得分:1)

尝试Parallel.For:https://msdn.microsoft.com/en-us/library/dd460713(v=vs.110).aspx

ParallelOptions options = new ParallelOptions();
options.MaxDegreeOfParallelism = 10; //max threads

Parallel.For(0, 45856582, options, i => { 
    Worker temp = new Worker(i, i + 10000);
    temp.DoWork();
} );