I've not tried the code, as I don't have a working example right now. But from what I've understood from MSDN, you should get Defferal when you plan to run async task and call Complete()
after you finish it.
BackgroundTaskDeferral _deferral;
public async void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
accessMediaUpload();
}
private async Task accessMediaUpload()
{
StorageFolder picfolder = KnownFolders.CameraRoll;
var x = await picfolder.GetFilesAsync();
var enumerator = x.GetEnumerator();
Debug.WriteLine("Number of files are: " + x.Count);
while (enumerator.MoveNext())
{
var file = enumerator.Current;
BackgroundUploader uploader = new BackgroundUploader();
uploader.SetRequestHeader("Filename", file.Name);
UploadOperation upload = uploader.CreateUpload(uri, file);
await upload.StartAsync();
// Get the HTTP response to see the upload result
ResponseInformation response = upload.GetResponseInformation();
if (response.StatusCode == 200)
{
Debug.WriteLine(file.Name + " Uplaoded");
}
}
_deferral.Complete();
}
Few remarks:
note that IMO you should put your
_deferral.Complete();
intofinally
block oftry-catch-finally
- just to ensure that it is called even there was an exception. As said at MSDNBe careful always to complete all obtained background task deferrals. The system does not suspend or terminate the background host process until all of its pending background task deferrals are complete. Leaving background task deferrals outstanding interferes with the system's ability to manage process lifetimes and will cause resources to leak.
the method above should be probably improved as you could get Defferal for each Task separately (if you have more than one) and call Complete at its end. This should allow you to run multiple Tasks and finish the whole
BackgroundTask
when all asynchronous Tasks are finished (calledComplete()
)