Xamarin Forms 中的下载取消延迟

Download cancel delay in Xamarin Forms

我需要下载 pdf 文件并保存在设备中。我已经使用 WebClient 进程下载文件并在下载过程中显示进度。

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

下载正常。要取消正在进行的下载,我使用了下面提到的 cancellationtokensource 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)
{
}

取消下载需要更多秒数。你能建议我减少取消下载的延迟吗?

我们必须在下载异步进程之前将令牌注册到 webclient 取消异步进程。我们必须维持如下秩序,

//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 设备上都可以正常工作。