從您的應用程式觸發背景工作Trigger a background task from within your app

了解如何使用 ApplicationTrigger 從您的應用程式啟動背景工作。Learn how to use the ApplicationTrigger to activate a background task from within your app.

如需如何建立應用程式觸發程式的範例,請參閱此 範例For an example of how to create an Application trigger, see this example.

本主題假設您有想要從應用程式啟動的背景工作。This topic assumes that you have a background task that you want to activate from your application. 如果您目前沒有背景工作,可以在 BackgroundActivity.cs 找到範例背景工作。If you don't already have a background task, there is a sample background task at BackgroundActivity.cs. 或者,依照建立和註冊跨處理序的背景工作中的步驟建立背景工作。Or, follow the steps in Create and register an out-of-process background task to create one.

為什麼要使用應用程式觸發程序Why use an application trigger

使用 ApplicationTrigger,在不同於前景應用程式的處理序中執行程式碼。Use an ApplicationTrigger to run code in a separate process from the foreground app. 如果 App 有工作需要在背景完成 (即使使用者關閉前景 App),很適合使用 ApplicationTriggerAn ApplicationTrigger is appropriate if your app has work that needs to be done in the background--even if the user closes the foreground app. 如果背景工作應於關閉 App 時停止,或應繫結於前景處理序的狀態,則必須改用延伸執行If background work should halt when the app is closed, or should be tied to the state of the foreground process, then Extended Execution should be used, instead.

建立應用程式觸發程序Create an application trigger

建立新的 ApplicationTriggerCreate a new ApplicationTrigger. 您可以依照下面片段的做法將其儲存在欄位中。You could store it in a field as is done in the snippet below. 這是為了方便起見,不必在稍後要發出訊號通知觸發程序時建立新的執行個體,This is for convenience so that we don't have to create a new instance later when we want to signal the trigger. 不過,您可以使用任何 ApplicationTrigger 執行個體來通知觸發程序。But you can use any ApplicationTrigger instance to signal the trigger.

// _AppTrigger is an ApplicationTrigger field defined at a scope that will keep it alive
// as long as you need to trigger the background task.
// Or, you could create a new ApplicationTrigger instance and use that when you want to
// trigger the background task.
_AppTrigger = new ApplicationTrigger();
// _AppTrigger is an ApplicationTrigger field defined at a scope that will keep it alive
// as long as you need to trigger the background task.
// Or, you could create a new ApplicationTrigger instance and use that when you want to
// trigger the background task.
Windows::ApplicationModel::Background::ApplicationTrigger _AppTrigger;
// _AppTrigger is an ApplicationTrigger field defined at a scope that will keep it alive
// as long as you need to trigger the background task.
// Or, you could create a new ApplicationTrigger instance and use that when you want to
// trigger the background task.
ApplicationTrigger ^ _AppTrigger = ref new ApplicationTrigger();

(選擇性) 新增條件(Optional) Add a condition

您可以建立背景工作條件來控制何時執行工作。You can create a background task condition to control when the task runs. 條件會在條件符合之前,一直讓背景工作無法執行。A condition prevents the background task from running until the condition is met. 如需詳細資訊,請參閱設定執行背景工作的條件For more information, see Set conditions for running a background task.

在此範例中,條件會設定為 InternetAvailable ,如此一來,一旦觸發之後,工作只會在網際網路存取可供使用時執行。In this example the condition is set to InternetAvailable so that, once triggered, the task only runs once internet access is available. 如需可用條件的清單,請參閱 SystemConditionTypeFor a list of possible conditions, see SystemConditionType.

SystemCondition internetCondition = new SystemCondition(SystemConditionType.InternetAvailable);
Windows::ApplicationModel::Background::SystemCondition internetCondition{
    Windows::ApplicationModel::Background::SystemConditionType::InternetAvailable };
SystemCondition ^ internetCondition = ref new SystemCondition(SystemConditionType::InternetAvailable)

如需有關背景觸發程序條件及類型的深入資訊,請參閱使用背景工作支援應用程式For more in-depth information on conditions and types of background triggers, see Support your app with background tasks.

呼叫 RequestAccessAsync()Call RequestAccessAsync()

註冊 ApplicationTrigger 背景工作之前,由於使用者可能已經停用 App 的背景活動,請呼叫 RequestAccessAsync 來判斷使用者允許的背景活動層級。Before registering the ApplicationTrigger background task, call RequestAccessAsync to determine the level of background activity the user allows because the user may have disabled background activity for your app. 如需有關使用者可如何控制背景活動設定的詳細資訊,請參閱最佳化背景活動See Optimize background activity for more information about the ways users can control the settings for background activity.

var requestStatus = await Windows.ApplicationModel.Background.BackgroundExecutionManager.RequestAccessAsync();
if (requestStatus != BackgroundAccessStatus.AlwaysAllowed)
{
   // Depending on the value of requestStatus, provide an appropriate response
   // such as notifying the user which functionality won't work as expected
}

註冊背景工作Register the background task

呼叫背景工作註冊函式以註冊背景工作。Register the background task by calling your background task registration function. 如需註冊背景工作的詳細資訊,並查看以下範例程式碼中 RegisterBackgroundTask() 方法的定義,請參閱註冊背景工作For more information on registering background tasks, and to see the definition of the RegisterBackgroundTask() method in the sample code below, see Register a background task.

如果您想要使用應用程式觸發程序來延長前景處理序的存留期,請考慮改用延伸執行If you are considering using an Application Trigger to extend the lifetime of your foreground process, consider using Extended Execution instead. 應用程式觸發程序是專為建立要用於執行工作的個別裝載處理序所設計。The Application Trigger is designed for creating a separately hosted process to do work in. 下列代碼片段會註冊跨處理序背景觸發程序。The following code snippet registers an out-of-process background trigger.

string entryPoint = "Tasks.ExampleBackgroundTaskClass";
string taskName   = "Example application trigger";

BackgroundTaskRegistration task = RegisterBackgroundTask(entryPoint, taskName, appTrigger, internetCondition);
std::wstring entryPoint{ L"Tasks.ExampleBackgroundTaskClass" };
std::wstring taskName{ L"Example application trigger" };

Windows::ApplicationModel::Background::BackgroundTaskRegistration task{
    RegisterBackgroundTask(entryPoint, taskName, appTrigger, internetCondition) };
String ^ entryPoint = "Tasks.ExampleBackgroundTaskClass";
String ^ taskName   = "Example application trigger";

BackgroundTaskRegistration ^ task = RegisterBackgroundTask(entryPoint, taskName, appTrigger, internetCondition);

背景工作註冊參數是在註冊之時進行驗證。Background task registration parameters are validated at the time of registration. 如果有任一個登錄參數無效,就會傳回錯誤。An error is returned if any of the registration parameters are invalid. 請確認您的 App 能夠妥善處理背景工作註冊失敗的狀況;反之,如果 App 需依賴有效的驗證物件,則在嘗試註冊工作之後,可能會當機。Ensure that your app gracefully handles scenarios where background task registration fails - if instead your app depends on having a valid registration object after attempting to register a task, it may crash.

觸發背景工作Trigger the background task

觸發背景工作之前,使用 BackgroundTaskRegistration 來驗證背景工作是否已註冊。Before you trigger the background task, use BackgroundTaskRegistration to verify that the background task is registered. 驗證所有背景工作是否皆已註冊的好時機是在 App 啟動時。A good time to verify that all of your background tasks are registered is during app launch.

藉由呼叫 ApplicationTrigger.RequestAsync 來觸發背景工作。Trigger the background task by calling ApplicationTrigger.RequestAsync. 任何 ApplicationTrigger 執行個體都適用。Any ApplicationTrigger instance will do.

請注意,無法從背景工作本身呼叫 ApplicationTrigger.RequestAsync,也無法在 App 處於背景執行狀態時這麼做 (如需應用程式狀態的詳細資訊,請參閱應用程式週期)。Note that ApplicationTrigger.RequestAsync can't be called from the background task itself, or when the app is in the background running state (see App lifecycle for more information about application states). 如果使用者已設定阻止 App 執行背景活動的能源或隱私權原則,這可能會傳回 DisabledByPolicyIt may return DisabledByPolicy if the user has set energy or privacy policies that prevent the app from performing background activity. 此外,一次也只有一個 AppTrigger 可以執行。Also, only one AppTrigger can run at a time. 如果您嘗試在另一個應用程式觸發程序已經在執行時執行 AppTrigger,函式將會傳回 CurrentlyRunningIf you attempt to run an AppTrigger while another is already running, the function will return CurrentlyRunning.

var result = await _AppTrigger.RequestAsync();

管理背景工作的資源Manage resources for your background task

使用 BackgroundExecutionManager.RequestAccessAsync 可判斷使用者是否已決定限制您的應用程式的背景活動。Use BackgroundExecutionManager.RequestAccessAsync to determine if the user has decided that your app’s background activity should be limited. 請留意您的電池使用量,並且只在需要完成使用者想要的動作時才在背景執行。Be aware of your battery usage and only run in the background when it is necessary to complete an action that the user wants. 如需有關使用者可如何控制背景活動設定的詳細資訊,請參閱最佳化背景活動See Optimize background activity for more information about the ways users can control the settings for background activity.

  • 記憶體︰調整 App 的記憶體和能源使用量是確保作業系統允許背景工作執行的關鍵。Memory: Tuning your app's memory and energy use is key to ensuring that the operating system will allow your background task to run. 使用記憶體管理 API 來了解您的背景工作正在使用多少記憶體。Use the Memory Management APIs to see how much memory your background task is using. 您的背景工作使用的記憶體越多,作業系統就越不容易在有其他 App 執行於前景時允許您的 App 繼續執行。The more memory your background task uses, the harder it is for the OS to keep it running when another app is in the foreground. 最終是由使用者控制您的應用程式可執行的所有背景活動,而且他也能看到您的應用程式對電池使用量的影響。The user is ultimately in control of all background activity that your app can perform and has visibility on the impact your app has on battery use.
  • CPU 時間:背景工作受限於其依據觸發程序類型所取得的實際執行使用時間量。CPU time: Background tasks are limited by the amount of wall-clock usage time they get based on trigger type. 應用程式觸發程序所觸發之背景工作的時間限制約為 10 分鐘。Background tasks triggered by the Application trigger are limited to about 10 minutes.

請參閱使用背景工作支援應用程式,以了解套用至背景工作的資源限制。See Support your app with background tasks for the resource constraints applied to background tasks.

備註Remarks

從 Windows 10 開始,使用者不需要將您的應用程式新增到鎖定畫面,就已經可以使用背景工作。Starting with Windows 10, it is no longer necessary for the user to add your app to the lock screen in order to utilize background tasks.

如果您已經先呼叫 RequestAccessAsync,背景工作將只會使用 ApplicationTrigger 來執行。A background task will only run using an ApplicationTrigger if you have called RequestAccessAsync first.