我正在使用C#语言为UWP编程 . 我正在阅读有关后台任务的内容,并创建并注册一个进程内后台任务 .
后台任务的注册码:
public static async Task RegisterBackgroundTask()
{
//
// Check for existing registrations of this background task.
//
foreach (var cur in BackgroundTaskRegistration.AllTasks.Values)
{
if (cur.Name == taskName) // The task is already registered.
return;
}
//
// Universal Windows apps must call RequestAccessAsync before registering any of the background trigger types.
// To ensure that your Universal Windows app continues to run properly after you release an update,
// you must call RemoveAccess and then call RequestAccessAsync when your app launches after being updated.
//
var requestAccess = await BackgroundExecutionManager.RequestAccessAsync();
if (requestAccess == BackgroundAccessStatus.DeniedByUser ||
requestAccess == BackgroundAccessStatus.DeniedBySystemPolicy)
return;
//
// Register the background task.
//
var builder = new BackgroundTaskBuilder();
builder.Name = taskName;
builder.SetTrigger(new TimeTrigger(15, false));
//builder.AddCondition(condition);
var task = builder.Register();
}
我的OnBackgroundActivated在App.cs中:
volatile bool _cancelRequested = false;
BackgroundTaskDeferral _deferral;
protected override async void OnBackgroundActivated(BackgroundActivatedEventArgs args)
{
base.OnBackgroundActivated(args);
// Query BackgroundWorkCost
// Guidance: If BackgroundWorkCost is high, then perform only the minimum amount
// of work in the background task and return immediately.
var cost = BackgroundWorkCost.CurrentBackgroundWorkCost;
if (cost == BackgroundWorkCostValue.High)
return;
args.TaskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
_deferral = args.TaskInstance.GetDeferral();
if (!_cancelRequested) // start one or more asynchronous methods using the await keyword
await BackgroundTaskExecution.UpdateTile();
_deferral.Complete();
}
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
_cancelRequested = true;
}
这些是我的代码 . 我运行这个程序,等待15分钟 . 我的瓷砖更新了 . 我再等15分钟 . 我的瓷砖再次更新 . 我使用Visual Studio 2017生命周期事件工具栏运行app并测试我的bacground任务 . 这很好用 .
所以我的代码没有问题 . 但如果我在部署之后关闭我的应用程序并再次等待15分钟,我的磁贴本身或使用工具栏工作
单击确定后,我的应用程序不再有后台任务,我必须再次注册 . 注册后我再次收到相同的错误并关闭应用程序并再次运行应用程序 . 我不知道为什么会这样 . 有可能帮助我吗?
Update 1:
我今天改变了我的代码,但今天我遇到了新问题 . 我在后台任务代码中运行BackgroundTaskExecution.UpdateTile() . BackgroundTaskExecution是我为我的项目创建的CommonClass库中的一个类 . 我把那个 class 搬到了我的主项目 . 现在我的项目工作的货物 . 我的后台任务再次部署我的应用后运行 . 它's work when I am in my app or outside of app. but there is new problem. I run background task with time or lifecycle toolbar when my app is running, it'的工作没有错误,但当我等待后台任务运行而我的应用程序没有运行时,我在后台任务中得到错误 . (我添加了try-catch块,当我的应用程序未运行时我收到异常消息并在tile上显示)错误消息是:
该应用程序调用了一个为不同线程编组的接口(来自HRESULT的异常:0x8001010E)(RPC_E_WRONG_THREAD)
所以这是我的新问题 . 为什么我的问题解决了我的课程到我的主项目?为什么我在使用应用内后台任务时出现此错误?
Update 2: 我删除了所有不必要的代码 . 我写了一个你点击按钮的应用程序 . 已注册后台任务,您可以使用更改时区更新磁贴 . 它已经完成了.2765528_工作了 . 请帮我 . Link Download Project
谢谢,我很抱歉英文类型 .