Search code examples
c#windows-phonewindows-phone-8.1background-task

Windows phone 8.1 background task memory management


background task in windows phone 8.1 has a limited 40mb memory. For media upload to a server or related tasks, 40mb is pretty less.

For example: I am calling the Function below from The RUN method of a TimerTriggerTask.

    private async void AccessMediaUpload()
    {
        try
        {
            // SavedPictures can be used for working with emulators
            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;

                // Setup the the uploader with the name of the file
                var uploader = new BackgroundUploader();
                uploader.SetRequestHeader("Filename", file.Name);

                // Start the upload
                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");
                }
                //Debug.WriteLine("HTTP Status Code:" + response.StatusCode);
            }
            _deferral.Complete();
        }

        catch (OutOfMemoryException e)
        {
            Debug.WriteLine(e.Message);
        }
    }

If i have about 10 pictures to upload, it dies out after 4 pictures due to OutOfMemoryException.

Is there a way to handle memory here? Please note i am using Background Transfer networking api which does all the chunking of files by itself.


Solution

  • Don't await the result of your upload.

    All you want to do in the BackgroundTask is to start your upload. At that point, you have handed it off to the BackgroundTransfer to manage for you. The point of the BackgroundTransfer is to handle your upload outside your application, it will upload when your app is suspended and can even continue after the phone is restarted.

    In your case, processing in a loop, by not awaiting you'll simply start to process the next file. If you want to output the message on success, use the Progress callback.