我正在实现一个应用程序,用户可以选择下载资产(大约 750MB 的图像,每个大小约为 50KB)。我无法使用常规的 HttpClient 执行此操作,因为如果用户按下主页按钮,SendAsync/GetAsync API 将无法在后台运行,并且当用户返回应用程序时会崩溃。
我唯一的选择是使用我正在使用的BackgroundTransferService,如下所示:-
for(...)//calling the download function here
DownloadImageToIsoStore(planImageUri, cemetery_id + "_plan_1.gif", countryName);
public void DownloadImageToIsoStore(Uri imageUri, string imageName,string countryName)
{
while ((BackgroundTransferService.Requests.Count()) >= 25) { Thread.Sleep(100); }//do not add if count is 25 since that is the limit. added this to wait till space frees up in the queue
BackgroundTransferRequest backgroundTransferRequest = new BackgroundTransferRequest(imageUri);
backgroundTransferRequest.Method = "GET";
backgroundTransferRequest.DownloadLocation = new Uri("shared/transfers/" + imageName, UriKind.RelativeOrAbsolute);//shared/transfers is the required directory
backgroundTransferRequest.Tag = countryName;//will check this when download is completed
backgroundTransferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
BackgroundTransferService.Add(backgroundTransferRequest);
backgroundTransferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(backgroundTransferRequest_TransferStatusChanged);
backgroundTransferRequest.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(backgroundTransferRequest_TransferProgressChanged);
}
void backgroundTransferRequest_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
{
long bytes = e.Request.BytesReceived;
Debug.WriteLine(bytes);
}
void backgroundTransferRequest_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
{
BackgroundTransferRequest backgroundTransferRequest = e.Request;
BackgroundTransferService.Remove(backgroundTransferRequest);
}
下载已成功完成,但由于某种原因,没有调用 backgroundTransferRequest_TransferProgressChanged 和 backgroundTransferRequest_TransferStatusChanged 事件,我无法释放下载队列以进行任何其他下载。
请帮忙!
谢谢