在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."。