Recherche…


Remarques

  • Pour enregistrer une tâche d'arrière-plan qui s'exécute dans un processus séparé, vous devez accéder à l'onglet "Déclarations" du package.appxmanifest et ajouter une nouvelle "tâche d'arrière-plan" et définir le point d'entrée.
  • L'enregistrement d'une tâche d'arrière-plan en un seul processus peut être effectué à l'aide de BackgroundTaskBuilder , mais l'application lancera une exception si vous enregistrez une tâche deux fois. Vous devez donc vérifier si vous avez déjà enregistré une tâche.
  • L'application doit avoir le droit d'enregistrer une nouvelle tâche, cela peut être fait en appelant BackgroundExecutionManager.RequestAccessAsync() , mais assurez-vous d'avoir réellement l'autorisation. L'appel renvoie le type d'accès ( BackgroundAccessStatus enum) qui indiquera si vous avez accès ou non.
  • Les tâches enregistrées sont conservées jusqu'à ce que le package soit désinstallé, mais il ne sera pas difficile de vérifier les tâches dont vous avez besoin à chaque lancement, un bogue survient!
  • Lorsque l'application est mise à jour, l'autorisation d'enregistrer une nouvelle tâche est révoquée. Pour que votre application continue de fonctionner après une mise à jour, en particulier si vous avez ajouté un nouveau registre de tâches, vous devez supprimer et demander l'accès via BackgroundAccessManager . Une méthode pour savoir si votre application est mise à jour consiste à enregistrer une autre tâche avec un SystemTrigger , le type de SystemTriggerType.ServicingComplete .

Enregistrement d'une tâche

/// <summary>
/// Registers a background task in the system waiting to trigger
/// </summary>
/// <param name="taskName">Name of the task. Has to be unique</param>
/// <param name="taskEntryPoint">Entry point (Namespace) of the class (has to implement IBackgroundTask and has to be in a Windows Runtime Component) to start</param>
/// <param name="trigger">What has to be triggered to start the task</param>
/// <param name="condition">Optional condition. Can be null</param>
/// <param name="recreateIfExists">Should the Task be recreated if it already exists?</param>
/// <returns></returns>
public BackgroundTaskRegistration RegisterTask(string taskName, string taskEntryPoint, IBackgroundTrigger trigger, IBackgroundCondition condition = null) {
    Debug.WriteLine("Try registering task: " + taskName);

    var builder = new BackgroundTaskBuilder {
        Name = taskName,
        TaskEntryPoint = taskEntryPoint
    };

    builder.SetTrigger(trigger);

    if (condition != null) {
        builder.AddCondition(condition);
    }

    try {
        var task = builder.Register();
        Debug.WriteLine("Task successfully registered");
        return task;
    } catch (Exception exception) {
        Debug.WriteLine("Error creating Task: " + exception);
        return null;
    }
}

Obtenir une tâche enregistrée par son nom

/// <summary>
/// Gets a BackgroundTask by its name
/// </summary>
/// <param name="taskName">Name of the task to find</param>
/// <returns>The found Task or null if none found</returns>
public BackgroundTaskRegistration TaskByName(string taskName) =>
       BackgroundTaskRegistration.AllTasks.FirstOrDefault(x => x.Value.Name.Equals(taskName)).Value as BackgroundTaskRegistration;

La tâche

public sealed class BackgroundTask : IBackgroundTask {

    private BackgroundTaskDeferral _deferral;

    /// <summary>
    /// Registers the listener to check if the button is pressed
    /// </summary>
    /// <param name="taskInstance">An interface to an instance of the background task. The system creates this instance when the task has been triggered to run.</param>
    public async void Run(IBackgroundTaskInstance taskInstance) {
        _deferral = taskInstance.GetDeferral();

        //Do async operations here

        _deferral.Complete();
    }
}

Vérifiez si la tâche est enregistrée

private bool IsTaskRegistered(string taskName) =>
        BackgroundTaskRegistration.AllTasks.Any(x => x.Value.Name.Equals(taskName));

Déclencher une tâche manuellement

var trigger = new ApplicationTrigger();
TaskHandlerMentionedInThisTutorial.RegisterTask(TaskName, entryPoint, trigger, null, true);    
await trigger.RequestAsync();

Annuler l'inscription d'une tâche

/// <summary>
/// Unregister a single background task with given name
/// </summary>
/// <param name="taskName">task name</param>
/// <param name="cancelTask">true if task should be cancelled, false if allowed to finish</param>
public void UnregisterTask(string taskName, bool cancelTask) =>
    BackgroundTaskRegistration.AllTasks.First(x => x.Value.Name.Equals(taskName)).Value?.Unregister(cancelTask);

/// <summary>
/// Unregister an active group of background tasks, which name contains given string
/// </summary>
/// <param name="taskNamePart">part of the task name</param>
/// <param name="cancelTask">true if tasks should be cancelled, false if allowed to finish</param>
public void UnregisterTasks(string taskNamePart, bool cancelTask)
{
    foreach (var task in BackgroundTaskRegistration.AllTasks.Where(x => x.Value.Name.Contains(taskNamePart)))
        task.Value.Unregister(cancelTask);
}

Enregistrer une tâche d'arrière-plan avec un déclencheur

La tâche en arrière-plan est un excellent moyen d'effectuer certains travaux lorsque votre application n'est pas en cours d'exécution. Avant de pouvoir utiliser alors, vous devrez les enregistrer.

Voici un exemple d'une classe de tâche en arrière-plan, y compris l'enregistrement avec un déclencheur et une condition et l'implémentation d'exécution

public sealed class Agent : IBackgroundTask
{    
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        // run the background task code
    }
    
    // call it when your application will start.
    // it will register the task if not already done
    private static IBackgroundTaskRegistration Register()
    {
        // get the entry point of the task. I'm reusing this as the task name in order to get an unique name
        var taskEntryPoint   = typeof(Agent).FullName;
        var taskName         = taskEntryPoint;
        
        // if the task is already registered, there is no need to register it again
        var registration            = BackgroundTaskRegistration.AllTasks.Select(x => x.Value).FirstOrDefault(x => x.Name == taskName);
        if(registration != null) return registration;
                        
        // register the task to run every 30 minutes if an internet connection is available
        var taskBuilder             = new BackgroundTaskBuilder();
        taskBuilder.Name            = taskName;
        taskBuilder.TaskEntryPoint  = taskEntryPoint;
        taskBuilder.SetTrigger(new TimeTrigger(30, false));
        taskBuilder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
        
        return taskBuilder.Register();
    }
}


Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow