4

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

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

下载工作正常。为了取消正在进行的下载,我使用了以下链接中提到的 canceltokensource。

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)
{
}

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

4

1 回答 1

0

我们必须在下载异步进程之前将令牌注册到 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 设备中都可以正常工作。

于 2017-11-08T04:33:43.890 回答