【发布时间】:2016-04-13 17:30:54
【问题描述】:
我一直在尝试在后台运行代码。到目前为止,我设法注册了任务,但从未执行 Run 方法。这是我目前所拥有的:
背景UWP:
[assembly: Xamarin.Forms.Dependency(typeof(App.UWP.BackgroundUWP))]
namespace App.UWP
{
class BackgroundUWP : IBackground
{
public async void RegisterAndStartTask()
{
string taskName = typeof(MyTask).Name;
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == taskName)
{
task.Value.Unregister(true);
break;
}
}
BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
ApplicationTrigger trigger = new ApplicationTrigger();
builder.Name = taskName;
builder.TaskEntryPoint = typeof(MyTask).FullName;
builder.SetTrigger(trigger);
BackgroundTaskRegistration t = builder.Register();
await trigger.RequestAsync();
}
}
}
我的任务:
namespace App.UWP
{
public sealed class MyTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
// this method isn't being called
}
}
}
清单:
<Extension Category="windows.backgroundTasks" EntryPoint="App.UWP.MyTask">
<BackgroundTasks>
<Task Type="systemEvent" />
</BackgroundTasks>
</Extension>
当我设置断点时,我的应用程序到达 await trigger.RequestAsync();。在控制台中,我注意到这条消息backgroundTaskHost.exe has exited with code 1。我能做些什么来解决这个问题?
编辑:
可能与this 问题有关。我的项目如下所示:
- 应用程序 (PCL)
- App.UWP
【问题讨论】:
-
据我所知,您不需要添加此 Run 方法。一个异步方法已经创建了一个任务。如果你把关键字等待你只是等待返回。如果不想等待返回,请移除 await
-
我按照 this 教程进行操作,它说我需要实现 IBackgroundTask,这会强制您实现 Run 方法。
-
我的错误,我不理解 backgroundTask 和自 8.1 以来的这个变化,我没有那样做。对不起,我帮不了你
标签: c# xamarin win-universal-app