I am implementing an app where the user will have the option of downloading the assets(approx 750MB in images, each of which is around 50KB in size). I cannot do this using the regular HttpClient since if the user presses the home button, the SendAsync/GetAsync APIs don't work in the background and crash when the user comes back to the application.
My only option here is to use the BackgroundTransferService which I am using as follows:-
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);
}
The downloads are completed successfully but for some reason, the backgroundTransferRequest_TransferProgressChanged and backgroundTransferRequest_TransferStatusChanged events are not getting called and I cannot free up the download queue for any additional downloads.
Please help!
Thanks
The problem was that I was running the loop that was calling the DownloadImageToIsoStore on the UI thread.
The transfer status changed and progress changed events also apparently need the UI thread. As soon as I moved the calling function to a separate thread, the status and progress changed events started firing as expected.