微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Xamarin android下载第二次尝试后挂起

如何解决Xamarin android下载第二次尝试后挂起

我确实在努力处理以下代码。 目前正在使用Xamarin Android应用。 我正在从网络服务器下载文件,但是如果网络中断,我想重试几次下载。但是在第二次引发异常之后,它不再继续下载。 第一次像魅力一样。

我还尝试了不使用Polly的情况,并在内置延迟的情况下递归地对其进行了尝试。引发异常后,下载将不再继续。 :-(知道是什么原因造成的吗? Android 9.0中内置了什么?

await Policy
    .Handle<networkonmainthreadException>()
    .Or<Java.Net.UnkNownHostException>()
    .Or<SSLException>()
    .WaitAndRetryAsync(new[]
    {
        TimeSpan.FromSeconds(1),TimeSpan.FromSeconds(5),TimeSpan.FromSeconds(10)
    })
    .ExecuteAsync(async () =>
    {
        totalRead = await DownloadFile(url,progress,totalRead,token);

    });

这是DownloadFileOpenStream函数

private async Task<long> DownloadFile(string url,IProgress<double> progress,long totalRead,CancellationToken token)
{
    // Step 1 : Get call using HttpClient
    var response = await _client.GetAsync(url,HttpCompletionoption.ResponseHeadersRead,token);

    if (!response.IsSuccessstatusCode)
    {
        throw new Exception(string.Format("The request returned with HTTP status code {0}",response.StatusCode));
    }

    // Step 2 : Filename
    var fileName = url.Split('/').Last();

    var buffer = new byte[bufferSize];

    // Step 3 : Get total of data
    var totalData = response.Content.Headers.ContentLength.GetValueOrDefault(-1L);

    // Step 4 : Get the full path
    var filePath = Path.Combine(_fileService.GetStorageFolderPath(),fileName);

    // Step 5 : Download data
    using (var fileStream = OpenStream(filePath,totalRead))
    {
        using (var inputStream = await response.Content.ReadAsstreamAsync())
        {
            int bytesRead;

            while ((bytesRead = inputStream.Read(buffer,buffer.Length)) > 0)
            {
                totalRead += bytesRead;

                // Write data on disk.
                await fileStream.WriteAsync(buffer,bytesRead);

                progress.Report((totalRead * 1d) / (totalData * 1d) * 100);
            }
            progress.Report(0);
        }
    }

    return totalRead;
}

private Stream OpenStream(string path,long totalRead)
{
    if (totalRead > 0)
    {
        return new FileStream(path,FileMode.Append,FileAccess.Write,FileShare.None,bufferSize);
    }
    else
    {
        return new FileStream(path,FileMode.Create,bufferSize);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。