C# 线程池并发下载文件

using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;

class Program
{
    private static int maxConcurrentDownloads = 5; // 最大并发下载数
    private static int currentDownloads = 0; // 当前正在下载的数量
    private static Queue<string> downloadUrls = new Queue<string>(); // 要下载的 URL 队列

    static void Main(string[] args)
    {
        // 添加要下载的 URL 到队列中
        downloadUrls.Enqueue("https://example.com/file1");
        downloadUrls.Enqueue("https://example.com/file2");
        downloadUrls.Enqueue("https://example.com/file3");
        downloadUrls.Enqueue("https://example.com/file4");
        downloadUrls.Enqueue("https://example.com/file5");
        downloadUrls.Enqueue("https://example.com/file6");
        downloadUrls.Enqueue("https://example.com/file7");

        // 创建固定大小的线程池
       **C#接单交流群452760896**
        ThreadPool.SetMaxThreads(maxConcurrentDownloads, maxConcurrentDownloads);

        while (downloadUrls.Count > 0)
        {
            // 如果当前下载数已经达到最大并发下载数,则等待一段时间再检查
            if (currentDownloads >= maxConcurrentDownloads)
            {
                Thread.Sleep(100);
                continue;
            }

            // 从队列中获取要下载的 URL,并创建新的工作线程开始下载
            string url = downloadUrls.Dequeue();
            Interlocked.Increment(ref currentDownloads);
            ThreadPool.QueueUserWorkItem(DownloadFile, url);
        }

        Console.WriteLine("All files have been downloaded.");
        Console.ReadLine();
    }

    static void DownloadFile(object state)
    {
        string url = (string)state;
        Console.WriteLine("Downloading {0}", url);

        try
        {
            // 使用 WebClient 下载文件
            using (WebClient client = new WebClient())
            {
                client.DownloadFile(url, url.Substring(url.LastIndexOf("/") + 1));
                Console.WriteLine("Downloaded {0}", url);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Failed to download {0}: {1}", url, ex.Message);
        }

        Interlocked.Decrement(ref currentDownloads); // 下载完成后将当前下载数减一
    }
}

在以上示例中,downloadUrls 队列中存储了要下载的文件 URL,在主循环中从队列中获取 URL 并使用 ThreadPool.QueueUserWorkItem 创建新的工作线程开始下载。由于设置了最大并发下载数为 5,因此如果当前下载数已经达到 5,则等待一段时间再检查。

DownloadFile 方法中,使用 WebClient 类下载文件。当下载完成后,将当前下载数减一。最终,当队列中的所有 URL 都被处理完毕后,程序输出 “All files have been downloaded.” 并等待用户输入任意键结束程序。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值