后台任务即是当应用程序处于挂起状态时,不会影响由于程序持起而带来的某些滞后而执行的一些后台操作,如下载文件、最新信息的推送等。当然,也应尽量减少一些没有必要的后台操作,保证电池的寿命。
后台任务处理一般用于以下几种情况:
4、共享文件
后台任务中一般经常会使用以下一些类和方法:
3、SystemTrigger 一个后台任务必须有一个明确的Trigger才执行后台任务,通过SetTrigger()添加,一般Trigger的类型有以下一些类型
Background task trigger type |
Trigger event |
When the background task is triggered |
ControlChannelTrigger |
ControlChannelTrigger |
On incoming messages on the control channel. |
MaintenanceTrigger |
MaintenanceTrigger |
It’s time for maintenance background tasks. |
PushNotificationTrigger |
PushNotificationTrigger |
A raw notification arrives on the WNS channel. |
SystemEventTrigger |
InternetAvailable |
The Internet becomes available. |
SystemEventTrigger |
LockScreenApplicationAdded |
An app tile is added to the lock screen. |
SystemEventTrigger |
LockScreenApplicationRemoved |
An app tile is removed from the lock screen. |
SystemEventTrigger |
ControlChannelReset |
A network channel is reset. |
SystemEventTrigger |
NetworkStateChange |
A network change such as a change in cost or connectivity occurs. |
SystemEventTrigger |
OnlineIdConnectedStateChange |
Online ID associated with the account changes. |
SystemEventTrigger |
ServicingComplete |
The system has finished updating an application. |
SystemEventTrigger |
SessionConnected |
The session is connected. |
SystemEventTrigger |
SessionDisconnected |
The session is disconnected. |
SystemEventTrigger |
SmsReceived |
A new SMS message is received by an installed mobile broadband device. |
SystemEventTrigger |
TimeZoneChange |
The time zone changes on the device (for example, when the system adjusts the clock for daylight saving time). |
SystemEventTrigger |
UserAway |
The user becomes absent. |
SystemEventTrigger |
UserPresent |
The user becomes present. |
TimeTrigger |
TimeTrigger |
A time event occurs. |
4、SystemCondition
说了这么多,先来创建一个简单的后台任务,功能非常简单,就是后台任务定时刷新UI:
第一步:先创建一个空白的Metro项目,项目名为BackgroundProject
前台页面放了两个按钮(注册Task、注销Task)、一个TextBlock控件(显示后台任务的状态)
第二步:创建一个Class Library,该类库用于实现后台的具体任务,项目名为BackgroundSecniao,需要特别注意的时,这里需要将该项目的输出更改为Winmd文件,不要默认生成DLL
第三步:在BackgroundSecniao中新建一个类TimerBackTask.cs类,该类必须继承IBackgroundTask接口
{
volatile bool _cancelRequested = false;
BackgroundTaskDeferral _deferral = null;
ThreadPoolTimer _periodicTimer = null;
uint _progress = 0;
IBackgroundTaskInstance _taskInstance;
public void Run(IBackgroundTaskInstance taskInstance)
{
taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
_deferral = taskInstance.GetDeferral();
_taskInstance = taskInstance;
_periodicTimer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(PeriodicTimerCallback), TimeSpan.FromMilliseconds(1000));
}
private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
{
_cancelRequested = true;
}
private void PeriodicTimerCallback(ThreadPoolTimer timer)
{
if ((_cancelRequested == false) && (_progress < 100))
{
_progress += 10;
_taskInstance.Progress = _progress;
}
else
{
_periodicTimer.Cancel();
var settings = ApplicationData.Current.LocalSettings;
var key = _taskInstance.Task.TaskId.ToString();
if (_cancelRequested)
{
settings.Values[key] = "Canceled";
}
else
{
settings.Values[key] = "Completed";
}
_deferral.Complete();
}
}
第四步:BackgroundProject中的Package.appxmanifest需要设置下,需要在声明中添加相应的后台任务
第五步:在Register按钮中先注册Task
实现BackgroundTaskProgressEventHandler和BackgroundTaskCompletedEventArgs事件
{
Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
var taskRegistration = sender as IBackgroundTaskRegistration;
var progressArgs = args as BackgroundTaskProgressEventArgs;
if ((taskRegistration != null) && (progressArgs != null))
{
tbProgress.Text = "Progress: " + progressArgs.Progress + "%";
}
});
}
void task_Completed(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)
{
Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
try
{
var taskCompletion = sender as IBackgroundTaskRegistration;
var completionArgs = args as BackgroundTaskCompletedEventArgs;
if ((taskCompletion != null) && (completionArgs != null))
{
var key = taskCompletion.TaskId.ToString();
var settings = ApplicationData.Current.LocalSettings;
tbProgress.Text = settings.Values[key].ToString();
}
}
catch (Exception ex)
{
}
});
}
{
if (cur.Value.Name == SampleBackgroundTaskName)
{
cur.Value.Unregister(true);
}
}
在本地运行调试时,需要将TimerBackTask挂起,才能看到效果,挂起设断点也可以Debug后台程序
后台任务还有好多东西要学习,如锁屏时后台任务的执行、推送、后台任务与程序的生命周期等,内容相当之多,上面的是最基本最简单的内容了!