Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在具有有限计数的多个线程上运行函数_C#_.net_Multithreading - Fatal编程技术网

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

C# 在具有有限计数的多个线程上运行函数,c#,.net,multithreading,C#,.net,Multithreading,假设我有一个列表,其中包含我要下载的文件列表,还有一个函数,它获取文件URL名称并下载它。我想下载最多4个并行下载。我知道我可以使用一个完美的解决方案: Parallel.ForEach ( Result, new ParallelOptions { MaxDegreeOfParallelism = 4 }, file => DownloadSingleFile(file)

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

        Parallel.ForEach
        (
        Result,
        new ParallelOptions { MaxDegreeOfParallelism = 4 },                
        file => DownloadSingleFile(file)
        );
但是如果我们不想使用这种方法,你有什么建议?你的想法中最好的是什么


谢谢。

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

一个好的老式
线程怎么样

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();
}
for(int i=0;i
{
尝试
{
(工作时)
{
file=DownloadSingleFile(blockingFileQueue.Dequeue());
}
}
捕获(中断异常)
{
//吃掉异常并退出线程
}
});
t、 IsBackground=true;
t、 Start();
}

你为什么不想使用“完美解决方案”?关于你的答案,有一些很棒的地方。虽然它有点“老式”,但我认为它很棒,只要稍加调整,它就会完美无瑕。