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.” 并等待用户输入任意键结束程序。