在C#中,可以使用HttpClient
类和Task
类来实现多线程下载。以下是一个简单的示例代码,演示如何使用多线程下载多个文件:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string[] urls = { "url1", "url2", "url3" }; // 定义要下载的文件URL
var tasks = new Task[urls.Length];
for (int i = 0; i < urls.Length; i++)
{
tasks[i] = DownloadFile(urls[i]);
}
await Task.WhenAll(tasks);
Console.WriteLine("All files downloaded successfully.");
}
static async Task DownloadFile(string url)
{
using (var client = new HttpClient())
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
var fileName = url.Substring(url.LastIndexOf('/') + 1);
using (var fileStream = System.IO.File.Create(fileName))
{
await response.Content.CopyToAsync(fileStream);
}
Console.WriteLine($"File {fileName} downloaded successfully.");
}
else
{
Console.WriteLine($"Failed to download file from {url}. Status code: {response.StatusCode}");
}
}
}
}
在上面的代码中,我们通过Task
类创建了多个下载文件的任务,并使用Task.WhenAll
方法等待所有任务完成。每个下载任务都使用HttpClient
类来发送HTTP请求并下载文件。当所有文件下载完成后,会输出"All files downloaded successfully."。