Search code examples
xamarin.iosxamarin.formsxamarin.androidcancellationtokensourcedownloadfileasync

Download cancel delay in Xamarin Forms


I need to download a pdf file and save in device. I have used WebClient process to download a file and show progress while downloading it.

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

Download is working properly. To cancel the download which is in progress, I have used cancellationtokensource as mentioned in below link.

https://learn.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 please suggest me to reduce the delay in cancelling download?


Solution

  • We have to register token into webclient cancel async process before downloadasync process. We have to maintain order like below,

    //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
    

    It doesn't takes even milliseconds and cancellation works fine in both Xamarin.Android and Xamarin.iOS device.