Why the cancellationToken not cancell the download at the middle?

42 Views Asked by At

I am downloading a 1GB file and I am trying to cancel, if I am fast and I press 'c' to cancel, the cancellation is donde, but if the downloan began, then the process download all the file, and at the end, the flag "Cancelled" is true

Why the cancellationToken not cancell the download at the middle?

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));

}

Example of cancelling fast:

Cancelling Fast

Example of trying to cancell after the download began

Trying to cancel when the download began

The download is cancelled, but the entire file was downloaded

0

There are 0 best solutions below