开发者

Run a function on multiple threads with a limited count

开发者 https://www.devze.com 2023-03-28 12:42 出处:网络
Let\'s say I have a list that contains list of files I want to download and a function that gets a file URL name and downloads it. I want to download at max 4 parallel downloads. I know I can use a pe

Let's say I have a list that contains list of files I want to download and a function that gets a file URL name and downloads it. I want to download at max 4 parallel downloads. I know I can use a perfect solution for this:

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

But what do you suggest if we don't want to use this meth开发者_JAVA技巧od? What is best in your idea?

Thank you.


How about a good old-fashioned Thread like this:

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();
}


We may start 4 threads or use ThreadPool to add 4 work items.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号