Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@LanceMcCarthy
Created July 21, 2016 20:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LanceMcCarthy/b2f2043b1f10592417a37c707fe62752 to your computer and use it in GitHub Desktop.
Save LanceMcCarthy/b2f2043b1f10592417a37c707fe62752 to your computer and use it in GitHub Desktop.
public static class TaskHelpers
{
public static async Task RegisterTaskAsync(string taskFriendlyName, string taskEntryPoint, uint taskRunFrequency, SystemConditionType condition = SystemConditionType.InternetAvailable)
{
try
{
//if task already exists, unregister it before adding it
foreach (var task in BackgroundTaskRegistration.AllTasks.Where(cur => cur.Value.Name == taskFriendlyName))
{
task.Value.Unregister(true);
}
var builder = new BackgroundTaskBuilder();
builder.Name = taskFriendlyName;
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(new TimeTrigger(taskRunFrequency, false));
builder.AddCondition(new SystemCondition(condition));
builder.Register();
}
catch (Exception ex)
{
await new MessageDialog($"RegisterTaskAsync Exception\r\n\nError: {ex.Message}").ShowAsync();
}
}
public static async Task<bool> CheckBackgroundTasksAsync(string taskFriendlyName)
{
try
{
await BackgroundExecutionManager.RequestAccessAsync();
return BackgroundTaskRegistration.AllTasks.Any(task => task.Value.Name == taskFriendlyName);
}
catch (Exception ex)
{
await new MessageDialog($"Something went wrong checking for background tasks. Error: {ex.Message}").ShowAsync();
return false;
}
}
public static async Task<bool> UnregisterTaskAsync(string taskFriendlyName)
{
try
{
await BackgroundExecutionManager.RequestAccessAsync();
foreach (var task in BackgroundTaskRegistration.AllTasks.Where(cur => cur.Value.Name == taskFriendlyName))
{
task.Value.Unregister(true);
return true;
}
return false;
}
catch (Exception ex)
{
await new MessageDialog($"UnregisterTaskAsync Exception\r\n\nError: {ex.Message}").ShowAsync();
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment