我正在下载一个 1GB 的文件,我正在尝试取消,如果我速度很快,我按“c”取消,取消是 donde,但如果下载开始,那么这个过程会下载所有文件,最后,标志“取消”为真
为什么cancellationToken中途不取消下载?
using System.Net;
Console.WriteLine("Hello, World!");
Console.WriteLine("Downloading a 100MB file...");
var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
DownloadFileWithToken(cancellationToken);
Console.WriteLine("Press C, to cancel the download");
if (Console.ReadKey().KeyChar == 'c')
{
cancellationTokenSource.Cancel();
Console.WriteLine("\n\rCancellation Sent");
}
Console.ReadLine();
void DownloadFileWithToken(CancellationToken token)
{
const string file1Gb = "https://speed.hetzner.de/1GB.bin";
var webClient = new WebClient();
token.Register(() => webClient.CancelAsync());
webClient.DownloadProgressChanged += (sender, e) =>
{
Console.WriteLine(e.BytesReceived);
};
webClient.DownloadDataCompleted += (sender, e) =>
{
if (!e.Cancelled)
{
byte[] data = (byte[])e.Result;
Console.WriteLine($"\nDownload Completed: {data.Length}");
}
else
{
Console.WriteLine("\nDownload canceled");
}
};
webClient.DownloadDataAsync(new Uri(file1Gb));
}
快速取消示例:
下载开始后尝试取消的例子