Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Nota
Artikel ini membahas tugas latar belakang yang dibangun dengan Windows Runtime (WinRT) BackgroundTaskBuilder API di Windows. ApplicationModel.Background namespace untuk aplikasi dengan identitas paket, termasuk UWP dan aplikasi desktop kemasan. Jika Anda membangun aplikasi baru atau memigrasikan aplikasi yang sudah ada ke SDK Aplikasi Windows, lihat Gunakan tugas latar belakang di aplikasi Windows dan strategi migrasi tugas Background.
Pelajari cara membuat dan mendaftarkan tugas latar belakang di aplikasi Anda dengan kelas Windows Runtime (WinRT) BackgroundTaskBuilder.
Mendaftarkan tugas latar belakang
Lihat sampel BackgroundTask untuk contoh lengkap mendaftarkan tugas latar belakang di aplikasi Universal Windows Platform (UWP).
Contoh berikut menunjukkan pendaftaran tugas Win32 COM yang berjalan pada timer berulang tiap 15 menit.
Untuk mendaftarkan tugas latar belakang, Anda harus terlebih dahulu membuat instans baru kelas BackgroundTaskBuilder . Kelas BackgroundTaskBuilder ini digunakan untuk membuat dan mendaftarkan tugas latar belakang di aplikasi Anda. Contoh kode berikut memperlihatkan bagaimana membuat instans kelas BackgroundTaskBuilder baru:
using System;
using Windows.ApplicationModel.Background;
public IBackgroundTaskRegistration RegisterBackgroundTaskWithSystem(IBackgroundTrigger trigger, Guid entryPointClsid, string taskName)
{
BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
builder.SetTrigger(trigger);
builder.SetTaskEntryPointClsid(entryPointClsid);
BackgroundTaskRegistration registration;
if (builder.Validate())
{
registration = builder.Register(taskName);
}
else
{
registration = null;
}
return registration;
}
RegisterBackgroundTaskWithSystem(new TimeTrigger(15, false), typeof(TimeTriggeredTask).GUID, typeof(TimeTriggeredTask).Name);
Metode ini RegisterBackgroundTaskWithSystem mengambil tiga parameter:
-
trigger: Pemicu yang akan memulai tugas latar belakang. -
entryPointClsid: ID kelas dari titik entri tugas latar belakang. -
taskName: Nama tugas latar belakang.
Metode RegisterBackgroundTaskWithSystem ini membuat instans baru dari kelas BackgroundTaskBuilder dan mengatur ID kelas pemicu serta titik masuk untuk tugas latar belakang. Metode kemudian mendaftarkan tugas latar belakang dengan sistem.
Nota
Kelas ini bukan bersifat agile, yang berarti Anda perlu mempertimbangkan model threading dan perilaku marshalingnya. Untuk informasi selengkapnya, lihat Threading and Marshaling (C++/CX) dan Gunakan objek Windows Runtime di lingkungan multithreaded (.NET).
Mengelola siaga canggih pada tugas latar belakang
BackgroundTaskBuilder dan API terkait sudah memungkinkan aplikasi desktop paket untuk menjalankan tugas latar belakang. API sekarang memperluas API-API ini untuk memungkinkan aplikasi ini menjalankan kode dalam mode siaga modern. Pembaruan ini juga menambahkan properti yang dapat diminta oleh aplikasi untuk menentukan apakah sistem akan membatasi tugas latar belakang aplikasi saat dalam mode siaga modern guna menghemat daya baterai. Ini memungkinkan skenario di mana aplikasi menerima panggilan VoIP atau pemberitahuan push lain saat dalam mode siaga modern.
Nota
"Aplikasi desktop yang dikemas" di bagian ini mengacu pada aplikasi Win32 yang memiliki identitas paket (yaitu, aplikasi Desktop Bridge atau Sparse Signed Packaged) dan memiliki fungsi utama (atau wmain) sebagai titik masuknya.
Contoh berikut menunjukkan bagaimana pengembang aplikasi dapat menggunakan BACKGROUNDTaskBuilder API untuk mendaftar paling banyak satu tugas dengan nama tugas yang ditentukan. Sampel juga menunjukkan cara memeriksa dan memilih pendaftaran tugas untuk dijalankan dalam siaga modern untuk tugas aplikasi yang paling penting.
// The following namespace is required for BackgroundTaskBuilder APIs.
using Windows.ApplicationModel.Background;
// The following namespace is required for API version checks.
using Windows.Foundation.Metadata;
// The following namespace is used for showing Toast Notifications. This
// namespace requires the Microsoft.Toolkit.Uwp.Notifications NuGet package
// version 7.0 or greater.
using Microsoft.Toolkit.Uwp.Notifications;
// Incoming calls are considered to be critical tasks to the operation of the app.
const string IncomingCallTaskName = "IncomingCallTask";
const string NotificationTaskName = "NotificationTask";
const string PrefetchTaskName = "PrefetchTask";
public static bool IsAllowedInBackground(BackgroundAccessStatus status) {
return ((status != BackgroundAccessStatus.Denied) &&
(status != BackgroundAccessStatus.DeniedBySystemPolicy) &&
(status != BackgroundAccessStatus.DeniedByUser) &&
(status != BackgroundAccessStatus.Unspecified));
}
public async void RegisterTask(IBackgroundTrigger trigger,
Guid entryPointClsid,
string taskName,
bool isRunInStandbyRequested)
{
var taskBuilder = new BackgroundTaskBuilder();
taskBuilder.SetTrigger(trigger);
taskBuilder.SetTaskEntryPointClsid(entryPointClsid);
// Only the most critical background work should be allowed to proceed in
// modern standby. Additionally, some platforms may not support modern
// or running background tasks in modern standby at all. Only attempt to
// request modern standby execution if both are true. Requesting network
// is necessary when running in modern standby to handle push notifications.
if (IsRunInStandbyRequested && taskBuilder.IsRunningTaskInStandbySupported)
{
var accessStatus = BackgroundExecutionManager.GetAccessStatusForModernStandby();
if (!IsAllowedInBackground(accessStatus)
{
await BackgroundExecutionManager.RequestAccessKindForModernStandby(
BackgroundAccessRequestKind.AllowedSubjectToSystemPolicy,
"This app wants to receive incoming notifications while your device is asleep");
}
accessStatus = BackgroundExecutionManager.GetAccessStatusForModernStandby();
if (IsAllowedInBackground(accessStatus)
{
taskBuilder.IsRunningTaskInStandbyRequested = true;
taskBuilder.IsNetworkRequested = true;
}
}
// Check that the registration is valid before attempting to register.
if (taskBuilder.IsRegistrationValid)
{
// If a task with the specified name already exists, it is unregistered
// before a new one is registered. Note this API may still fail from
// catastrophic failure (e.g., memory allocation failure).
taskBuilder.Register(taskName);
}
return;
}
RegisterTask(new PushNotificationTrigger(), "{INSERT-YOUR-GUID-HERE}", IncomingCallTaskName, true);
Periksa apakah tugas latar belakang telah melebihi anggarannya saat dalam mode siaga modern
Contoh kode berikut menunjukkan bagaimana pengembang aplikasi dapat menggunakan BackgroundWorkCost.WasApplicationThrottledInStandby dan BackgroundWorkCost.ApplicationEnergyUseLevel untuk memantau dan bereaksi terhadap tugas latar belakang mereka menghabiskan anggaran aplikasinya. Pengembang aplikasi dapat bereaksi dengan mengurangi pekerjaan prioritas yang lebih rendah yang dilakukan dalam siaga modern. Perhatikan bahwa ini bergantung pada kode dari sampel sebelumnya.
public async void ReduceBackgroundCost()
{
BackgroundTaskRegistration callTask;
BackgroundTaskRegistration notificationTask;
BackgroundTaskRegistration prefetchTask;
// Nothing to do if the app was not or will not be throttled.
if (!BackgroundWorkCost.WasApplicationThrottledInStandby &&
(BackgroundWorkCost.ApplicationEnergyUseLevel != StandbyEnergyUseLevel.OverBudget))
{
return;
}
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
switch (task.Value.Name) {
case IncomingCallTaskName:
callTask = task.Value;
break;
case NotificationTaskName:
notificationTask = task.Value;
break;
case PrefetchTaskName:
prefetchTask = task.Value;
break;
default:
}
}
if (callTask.WasTaskThrottledInStandby)
{
// Unset the throttle flag after acknowledging it so the app can
// react to the same task being throttled again in the future.
task.Value.WasTaskThrottledInStandby = false;
// Notify the user that the notification was missed.
new ToastContentBuilder()
.AddText("You missed a call")
.AddText(task.Value.Name)
.Show();
// Because the incoming calls were not activated, demote less notifications
// tasks so the calls can be delivered promptly in the future.
RegisterTask(notificationTask.Value.Trigger,
typeof(TimeTriggeredTask).GUID,
notificationTask.Value.Name,
false);
}
// Note that if incoming call tasks were throttled in some previous modern
// standby session, the application energy use was over budget for some period.
// Demote unimportant tasks like prefetch work to avoid calls and notifications
// from being throttled.
if (callTask.WasTaskThrottledInStandby) ||
(BackgroundWorkCost.ApplicationEnergyUseLevel == StandbyEnergyUseLevel.OverBudget))
{
RegisterTask(prefetchTask.Value.Trigger,
typeof(TimeTriggeredTask).GUID,
prefetchTask.Value.Name,
false);
}
return;
}
Memantau tren penggunaan energi tugas latar belakang
Berikut ini adalah pembaruan ujung ke ujung bertahap ke kode sampel C++WinRT/C# berikut pada GitHub.
Contoh menunjukkan bagaimana Anda dapat menggunakan BackgroundWorkCost.ApplicationEnergyUseTrend untuk memantau bagaimana tren tugas latar belakang Anda menuju penghabisan anggaran mereka. Anda juga dapat menghentikan tugas latar belakang paling mahal dari berjalan saat dalam mode siaga modern, dan mencegah tugas latar belakang berjalan dalam mode siaga modern jika aplikasi tersebut menggunakan anggarannya terlalu cepat. Sampel ini bergantung pada kode dari sampel sebelumnya.
public async void ReduceBackgroundCostPreemptively()
{
BackgroundTaskRegistration mostExpensiveTask = null;
// We can't do anything preemptively since the trend isn't known.
if (!BackgroundWorkCost.IsApplicationEnergyUseTrendKnown)
{
return;
}
// The app is not trending towards being over budget, so this method can
// return early.
if ((BackgroundWorkCost.ApplicationEnergyUseTrend != EnergyUseTrend.OverBudget) &&
(BackgroundWorkCost.ApplicationEnergyUseTrend != EnergyUseTrend.OverHalf))
{
return;
}
// The application is going exceeding its budget very quickly. Demote the
// most expensive task that is not the call task before call tasks start being
// throttled.
if (BackgroundWorkCost.ApplicationEnergyUseTrend == EnergyUseTrend.OverBudget)
{
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if ((task.Value.Name != IncomingCallTaskName) &&
((mostExpensiveTask == null) ||
(mostExpensiveTask.ApplicationEnergyUseTrendContributionPercentage <
task.Value.ApplicationEnergyUseTrendContributionPercentage)))
{
mostExpensiveTask = task.Value;
}
}
}
if (mostExpensiveTask != null)
{
RegisterTask(mostExpensiveTask.Trigger,
typeof(TimeTriggeredTask).GUID,
mostExpensiveTask.Name,
false);
}
// The application is trending toward eventually exceeding its budget. Demote the
// least important prefetch task before calls and notifications are throttled.
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name == PrefetchTaskName) {
RegisterTask(task.Value.Trigger,
typeof(TimeTriggeredTask).GUID,
task.Value.Name,
false);
}
}
return;
}
Tugas latar belakang dan konektivitas jaringan
Jika tugas latar belakang Anda memerlukan konektivitas jaringan, ketahui pertimbangan berikut.
Pemicu terkait jaringan
- Gunakan SocketActivityTrigger untuk mengaktifkan tugas latar belakang saat paket diterima dan Anda perlu melakukan tugas berumur pendek. Setelah melakukan tugas, tugas latar belakang harus dihentikan untuk menghemat daya.
- Gunakan ControlChannelTrigger untuk mengaktifkan tugas latar belakang saat paket diterima dan Anda perlu melakukan tugas berumur panjang.
Kondisi dan bendera terkait jaringan
- Tambahkan kondisi InternetAvailable (BackgroundTaskBuilder.AddCondition) ke tugas latar belakang Anda untuk menunda pemicu tugas latar belakang hingga tumpukan jaringan berjalan. Kondisi ini menghemat daya karena tugas latar belakang tidak akan dijalankan hingga akses jaringan tersedia. Kondisi ini tidak memberikan aktivasi real-time.
- Terlepas dari pemicu yang Anda gunakan, atur IsNetworkRequested pada tugas latar belakang Anda untuk memastikan bahwa jaringan tetap aktif saat tugas latar belakang berjalan. Ini memberi tahu infrastruktur tugas latar belakang untuk menjaga jaringan tetap aktif saat tugas dijalankan, bahkan jika perangkat telah memasuki mode Siaga Tersambung. Jika tugas latar belakang Anda tidak menggunakan IsNetworkRequested, maka tugas latar belakang Anda tidak akan dapat mengakses jaringan ketika dalam mode Siaga Tersambung.
Konten terkait
Windows developer