xamarin.ios – 下载Xamarin Forms中的取消延迟

前端之家收集整理的这篇文章主要介绍了xamarin.ios – 下载Xamarin Forms中的取消延迟前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要下载pdf文件并保存在设备中.我已经使用WebClient进程下载文件并在下载时显示进度.

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

下载工作正常.要取消正在进行的下载,我使用了如下所述的cancellationtokensource链接.

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

取消下载需要几秒钟.你能建议我减少取消下载的延迟吗?

解决方法

我们必须在downloadasync进程之前将令牌注册到webclient cancel async进程.我们必须保持如下的顺序,

//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设备中都能正常工作.

猜你在找的iOS相关文章