Download cancellation delay in Xamarin Forms

I need to download a pdf file and save it on the device. I used the WebClient process to download the file and display the progress when it was downloaded.

CancellationTokenSource Token= new CancellationTokenSource(); //Initialize a token while start download
webClient.DownloadFileTaskAsync(new Uri(downloadurl), saveLocation); // Download file

Download is working correctly. To cancel the download that is in progress, I used cancelationtokensource as indicated in the following link.

https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads

Token.Cancel(); //Cancellation download

try
{
// check whether download cancelled or not
Token.ThrowIfCancellationRequested();
if(Token.IsCancellationRequested)
{
  //Changed button visibility
}
}
catch (OperationCanceledException ex)
{
}

It takes more seconds to cancel the download. Can you suggest me to reduce the delay when canceling the download?

+4
source share
1 answer

webclient downloadasync. , ,

//Initialize for download process
WebClient webClient = new WebClient();
CancellationTokenSource token = new CancellationTokenSource();

//register token into webclient
token.Register(webClient.CancelAsync);
try
{
  webClient.DownloadFileTaskAsync(new Uri(downloadurl), saveLocation); // Download a file
}
catch(Exception ex)
{
  //Change button visibility
}

Token.Cancel(); //Cancellation download put in cancel click button event

, Xamarin.Android, Xamarin.iOS.

0

Source: https://habr.com/ru/post/1688116/


All Articles