我需要下载一个pdf文件并保存在设备中。我使用WebClient进程下载文件并在下载时显示进度。
CancellationTokenSource Token= new CancellationTokenSource(); //Initialize a token while start download
webClient.DownloadFileTaskAsync(new Uri(downloadurl), saveLocation); // Download file
下载工作正常。要取消正在进行的下载,我使用了以下链接中提到的取消令牌源。
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)
{
}
取消下载需要更多秒数。你能建议我减少取消下载的延迟吗?
我们必须在下载异步过程之前将令牌注册到 Web 客户端取消异步过程中。我们必须维持如下秩序,
//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设备中都可以正常工作。