对于 Windows 8 应用程序,我尝试在 C#/Xaml 中注册后台任务。很难说,但我猜我的后台任务注册得很好,但是当我在调试位置工具栏上单击我的后台任务的名称时,我的应用程序停止工作而没有任何消息。
我查看了事件查看器上的日志,我得到:“具有入口点 MyApp.Pages.SampleBackgroundTask 和名称示例每小时后台任务的后台任务无法激活,错误代码为 0x80010008。”
这是我的代码:
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");
}
我在清单中添加了这个:
<Extension Category="windows.backgroundTasks" EntryPoint="MyApp.Pages.SampleBackgroundTask">
<BackgroundTasks>
<Task Type="timer" />
</BackgroundTasks>
</Extension>
我是不是忘记了什么?
谢谢您的帮助。
编辑:这是我的任务的代码,在我的项目页面之一中:
public sealed class SampleBackgroundTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
_deferral.Complete();
}
}