【发布时间】:2021-09-11 23:00:23
【问题描述】:
我有一个程序 (.NET 5),它使用 WebClient.DownloadFile 同时下载一堆文件 (1k+),它在使用调试器运行时按预期工作,在调试和发布模式下下载大约 99% 的文件;但是在没有调试器的情况下运行时,它无法下载超过 50% 的文件。
所有线程在程序结束之前完成,因为它们是前台线程。
程序的代码是:
using System;
using System.IO;
using System.Net;
using System.Threading;
namespace Dumper
{
internal sealed class Program
{
private static void Main(string[] args)
{
Directory.CreateDirectory(args[1]);
foreach (string uri in File.ReadAllLines(args[0]))
{
string filePath = Path.Combine(args[1], uri.Split('/')[^1]);
new Thread((param) =>
{
(string path, string url) = ((string, string))param!;
using WebClient webClient = new();
try
{
webClient.DownloadFile(new Uri(url.Replace("%", "%25")), path);
Console.WriteLine($"{path} has been successfully download.");
}
catch (UriFormatException)
{
throw;
}
catch (Exception e)
{
Console.WriteLine($"{path} failed to download: {e}");
}
}).Start((filePath, uri));
}
}
}
}
【问题讨论】:
-
失败怎么办?具体一点。
-
“不使用调试器运行”到底是什么意思?
RELEASE模式? -
您没有等待线程完成,所以程序将在
Main结束时结束。无论如何,1000 个线程和 1000 个 TCP 套接字听起来都是个坏主意 -
这个答案是一个如何等待线程完成的例子:stackoverflow.com/a/4190969/1233305
-
那么会发生什么?你得到什么异常,你得到控制台输出吗?