在具有有限计数的多个线程上运行函数

时间:2011-08-15 23:58:47

标签: c# .net multithreading

假设我有一个列表,其中包含我要下载的文件列表以及一个获取文件URL名称并下载它的函数。我想下载最多4个并行下载。我知道我可以使用完美的解决方案:

        Parallel.ForEach
        (
        Result,
        new ParallelOptions { MaxDegreeOfParallelism = 4 },                
        file => DownloadSingleFile(file)
        );

但是如果我们不想使用这种方法,你有什么建议?你的想法最好的是什么?

谢谢。

2 个答案:

答案 0 :(得分:3)

这样的老式Thread怎么样:

for(int i = 0; i < numThreads; i++)
{
    Thread t = new Thread(()=>
    {
        try
        {
            while(working)
            {
                file = DownloadSingleFile(blockingFileQueue.Dequeue());
            }
        }
        catch(InterruptException)
        {
            // eat the exception and exit the thread
        }
    });
    t.IsBackground = true;
    t.Start();
}

答案 1 :(得分:0)

我们可以启动4个线程或使用ThreadPool添加4个工作项。

相关问题