Can't register a Time triggered Background Task

8

For a Windows 8 App, in C#/Xaml I try to register a background task. It's hard to tell but I guess my background task is well registred but when I click on the name of my background task on the Debug Location Toolbar my app stops working without any message.

I looked at the log on the Event Viewer and I get : "The background task with entry point MyApp.Pages.SampleBackgroundTask and name Example hourly background task failed to activate with error code 0x80010008."

Here is my code :

   private async void Button_Click_BackgroundTask(object sender, RoutedEventArgs e)
    {
        string entryPoint = "MyApp.Pages.SampleBackgroundTask";
        string taskName = "Example hourly background task";
        TimeTrigger hourlyTrigger = new TimeTrigger(60, false);

        BackgroundTaskRegistration myBackGroundTaskRegistration =   RegisterBackgroundTask(entryPoint, taskName, hourlyTrigger, null);
        if(myBackGroundTaskRegistration != null)
        AttachProgressAndCompletedHandlers(myBackGroundTaskRegistration);
    }


   public static BackgroundTaskRegistration RegisterBackgroundTask(String taskEntryPoint,
                                                                    String name,
                                                                    IBackgroundTrigger trigger,
                                                                    IBackgroundCondition condition)
    {

        var taskRegistered = false;
        var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.AllTasks;

        foreach (var item in iter)
        {
            var task = item.Value;
            if (task.Name == name)
            {
                taskRegistered = true;
                return item.Value as BackgroundTaskRegistration;
            }
        }


        var builder = new BackgroundTaskBuilder();

        builder.Name = name;
        builder.TaskEntryPoint = taskEntryPoint;
        builder.SetTrigger(trigger);

        if (condition != null)
        {

            builder.AddCondition(condition);
        }

        BackgroundTaskRegistration taskBack = builder.Register();

        return taskBack;
    }


       private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
    {
        task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
        task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
    }


  private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
    {
        var progress = "Progress: " + args.Progress + "%";

    }


    private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
    {
        Debug.WriteLine("Hi");
    }

I added this in the manifest :

      <Extension Category="windows.backgroundTasks" EntryPoint="MyApp.Pages.SampleBackgroundTask">
      <BackgroundTasks>
        <Task Type="timer" />
      </BackgroundTasks>
    </Extension>

Did I forget something?

Thank you for your help.

EDIT : here is the code of my Task, within one of my project page :

      public sealed class SampleBackgroundTask : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();

        _deferral.Complete();
    }
}
c#
windows-8
microsoft-metro
asked on Stack Overflow Oct 24, 2012 by Thomas Salandre • edited Oct 25, 2012 by Thomas Salandre

5 Answers

6

I had this problem too. I also had mine in the same project. I finally got it to work by moving the task into a separate project. I had to set the project output as windows runtime component(under properties applicaiton tab) . Also don't forget to add the project as a reference.

answered on Stack Overflow Nov 12, 2012 by Bradley
3

You need user permission before you can run a BackgroundTask you can either do this manually: by opening the app and clicking Permissions in the Settings Charm and turning the Lock screen setting to on.

You can also prompt the user when the first screen is loaded with this:

BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();

Needless to say the latter is going to lead to a much better user experience.

answered on Stack Overflow Dec 27, 2012 by Tim
3

Two years later, now WinRT in Windows 10, Visual Studio 2015. Again, the same problem.

The asker has indicated that their background task was residing in the same project. That won't work: A very thorough article on background tasks is here. Also, as Tim noted, BackgroundExecutionManager.RequestAccessAsync() has to be called first. Since 8.1, though, when that is omitted, the background task registration will fail in that case, so you would never get to the place where the task trigger fails.

To sum up the requirements:

  • 'await BackgroundExecutionManager.RequestAccessAsync()' first
  • Task class must be in a Windows Runtime Component project
  • The Windows Runtime Component project must be referenced in the calling app
  • The task class must be declared in the app's manifest as above, with full namespace name
  • The Windows Runtime Component project and the App that uses it must target the same Windows version. Solution Explorer in Visual Studio -> Right-click on the project -> Properties -> Application resp. Library tab -> Targeting -> Target and Target version.

In my example, I had definitely done all of these, yet the task would not be triggered. The debug trace showed "The program '[0x72C] backgroundTaskHost.exe' has exited with code 1", the debugger broke on an ExecutionEngineException, and the event log of the target machine (Applications and Services Logs -> Microsoft -> Windows -> BackgroundTaskInfrastructure -> Operational) listed all kinds of creative completely undocumented windows error codes:

"The background task with entry point and name failed to activate with error code 0x8007001F (resp. 0x800706BE / 0x80131509)."

The failures were erratic: At first, they only happened rarely, and got worse over several successive program runs, until the background task was never called any more.

When the namespace name of the background tasks was changed (in all of the task registration, the package manifest, and the code), this fixed the error at first, and then also got worse over time.

The special circumstance in this case was that the app was developed on a remote target machine and debugged with the remote debugger. Removing the app package before each debugger run got rid of the errors.

So, these errors when running a background task (0x8007001F / 0x800706BE / 0x80131509) appear to have to do with not finding the registered task correctly. It might help to make sure that the task is correctly deregistered, and to remove the app package before running a new modification. Powershell command:

Get-AppPackage | where name -eq <myAppPackageGuid> | Remove-AppPackage

Just documenting this here in case someone has the same problem.

answered on Stack Overflow May 5, 2016 by J S • edited May 6, 2016 by J S
2

Add your Background Task Project into Main Project at reference and rebuild. it will work

answered on Stack Overflow Jan 27, 2013 by RaymondLe
0

The issue I had while writing background tasks was that in windows 10 under settings->Privacy->Background apps, I had to enable the option to allow apps to run in the background. Hope this helps someone!

answered on Stack Overflow Feb 27, 2018 by bdwhat

User contributions licensed under CC BY-SA 3.0