監視背景工作進度和完成Monitor background task progress and completion

重要 APIImportant APIs

了解 App 如何辨識在跨處理序中執行之背景工作所報告的進度與完成。Learn how your app can recognize progress and completion reported by a background task that runs out-of-process. (針對同處理序背景工作,您可以設定共用變數來表示進度和完成)。(For in-process background tasks, you can set shared variables to signify progress and completion.)

背景工作的進度和完成可以透過 App 程式碼監視。Background task progress and completion can be monitored by app code. 若要執行這項作業,App 要訂閱已向系統註冊之背景工作的事件。To do so, the app subscribes to events from the background task(s) it has registered with the system.

建立事件處理常式,以處理完成的背景工作。Create an event handler to handle completed background tasks

步驟 1Step 1

建立事件處理常式函式,以處理完成的背景工作。Create an event handler function to handle completed background tasks. 此程式碼必須遵循特定的使用量,以取得 IBackgroundTaskRegistration 物件和 BackgroundTaskCompletedEventArgs 物件。This code needs to follow a specific footprint, which takes an IBackgroundTaskRegistration object and a BackgroundTaskCompletedEventArgs object.

使用下列 OnCompleted 背景工作事件處理常式方法的使用量。Use the following footprint for the OnCompleted background task event handler method.

private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
{
    // TODO: Add code that deals with background task completion.
}
auto completed{ [this](
        Windows::ApplicationModel::Background::BackgroundTaskRegistration const& /* sender */,
        Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs const& /* args */)
{
    // TODO: Add code that deals with background task completion.
} };
auto completed = [this](BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
{
    // TODO: Add code that deals with background task completion.
};

步驟 2Step 2

將程式碼新增至會處理背景工作完成的事件處理常式。Add code to the event handler that deals with the background task completion.

例如,背景工作範例會更新 UI。For example, the background task sample updates the UI.

private void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
{
    UpdateUI();
}
auto completed{ [this](
        Windows::ApplicationModel::Background::BackgroundTaskRegistration const& /* sender */,
        Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs const& /* args */)
{
    UpdateUI();
} };
auto completed = [this](BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
{    
    UpdateUI();
};

建立事件處理常式函式,以處理背景工作進度。Create an event handler function to handle background task progress

步驟 1Step 1

建立事件處理常式函式,以處理完成的背景工作。Create an event handler function to handle completed background tasks. 這個程式碼需要遵循特定的配置,其中包括 IBackgroundTaskRegistration 物件與 BackgroundTaskProgressEventArgs 物件:This code needs to follow a specific footprint, which takes in an IBackgroundTaskRegistration object and a BackgroundTaskProgressEventArgs object:

針對 OnProgress 背景工作事件處理常式方式使用下列配置:Use the following footprint for the OnProgress background task event handler method:

private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
{
    // TODO: Add code that deals with background task progress.
}
auto progress{ [this](
    Windows::ApplicationModel::Background::BackgroundTaskRegistration const& /* sender */,
    Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs const& /* args */)
{
    // TODO: Add code that deals with background task progress.
} };
auto progress = [this](BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
{
    // TODO: Add code that deals with background task progress.
};

步驟 2Step 2

將程式碼新增至會處理背景工作完成的事件處理常式。Add code to the event handler that deals with the background task completion.

例如,背景工作範例會使用透過 args 參數所傳遞的進度狀態來更新 UI:For example, the background task sample updates the UI with the progress status passed in via the args parameter:

private void OnProgress(IBackgroundTaskRegistration task, BackgroundTaskProgressEventArgs args)
{
    var progress = "Progress: " + args.Progress + "%";
    BackgroundTaskSample.SampleBackgroundTaskProgress = progress;
    UpdateUI();
}
auto progress{ [this](
    Windows::ApplicationModel::Background::BackgroundTaskRegistration const& /* sender */,
    Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs const& args)
{
    winrt::hstring progress{ L"Progress: " + winrt::to_hstring(args.Progress()) + L"%" };
    BackgroundTaskSample::SampleBackgroundTaskProgress = progress;
    UpdateUI();
} };
auto progress = [this](BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
{
    auto progress = "Progress: " + args->Progress + "%";
    BackgroundTaskSample::SampleBackgroundTaskProgress = progress;
    UpdateUI();
};

使用新的和現有的背景工作來登錄事件處理函式Register the event handler functions with new and existing background tasks

步驟 1Step 1

當應用程式第一次登錄背景工作時,它應該登錄以接收其進度和完成更新,以防應用程式在前景仍然為使用中時執行工作。When the app registers a background task for the first time, it should register to receive progress and completion updates for it, in case the task runs while the app is still active in the foreground.

例如,背景工作範例會在它登錄的每個背景工作上呼叫下列函式:For example, the background task sample calls the following function on each background task that it registers:

private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration task)
{
    task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
    task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
}
void SampleBackgroundTask::AttachProgressAndCompletedHandlers(Windows::ApplicationModel::Background::IBackgroundTaskRegistration const& task)
{
    auto progress{ [this](
        Windows::ApplicationModel::Background::BackgroundTaskRegistration const& /* sender */,
        Windows::ApplicationModel::Background::BackgroundTaskProgressEventArgs const& args)
    {
        winrt::hstring progress{ L"Progress: " + winrt::to_hstring(args.Progress()) + L"%" };
        BackgroundTaskSample::SampleBackgroundTaskProgress = progress;
        UpdateUI();
    } };

    task.Progress(progress);

    auto completed{ [this](
        Windows::ApplicationModel::Background::BackgroundTaskRegistration const& /* sender */,
        Windows::ApplicationModel::Background::BackgroundTaskCompletedEventArgs const& /* args */)
    {
        UpdateUI();
    } };

    task.Completed(completed);
}
void SampleBackgroundTask::AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration^ task)
{
    auto progress = [this](BackgroundTaskRegistration^ task, BackgroundTaskProgressEventArgs^ args)
    {
        auto progress = "Progress: " + args->Progress + "%";
        BackgroundTaskSample::SampleBackgroundTaskProgress = progress;
        UpdateUI();
    };

    task->Progress += ref new BackgroundTaskProgressEventHandler(progress);

    auto completed = [this](BackgroundTaskRegistration^ task, BackgroundTaskCompletedEventArgs^ args)
    {
        UpdateUI();
    };

    task->Completed += ref new BackgroundTaskCompletedEventHandler(completed);
}

步驟 2Step 2

當應用程式啟動或是瀏覽至背景工作狀態是相關的新頁面時,它應該取得目前登錄的背景工作清單,並將它們與進度和完成事件處理函式關聯。When the app launches, or navigates to a new page where background task status is relevant, it should get a list of background tasks currently registered and associate them with the progress and completion event handler functions. 應用程式目前登錄的背景工作清單保留在 BackgroundTaskRegistration.AllTasks 屬性中。The list of background tasks currently registered by the application is kept in the BackgroundTaskRegistration.AllTasks property.

例如,背景工作範例會使用下列程式碼來附加瀏覽 SampleBackgroundTask 頁面時要執行的事件處理常式:For example, the background task sample uses the following code to attach event handlers when the SampleBackgroundTask page is navigated to:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    foreach (var task in BackgroundTaskRegistration.AllTasks)
    {
        if (task.Value.Name == BackgroundTaskSample.SampleBackgroundTaskName)
        {
            AttachProgressAndCompletedHandlers(task.Value);
            BackgroundTaskSample.UpdateBackgroundTaskStatus(BackgroundTaskSample.SampleBackgroundTaskName, true);
        }
    }

    UpdateUI();
}
void SampleBackgroundTask::OnNavigatedTo(Windows::UI::Xaml::Navigation::NavigationEventArgs const& /* e */)
{
    // A pointer back to the main page. This is needed if you want to call methods in MainPage such
    // as NotifyUser().
    m_rootPage = MainPage::Current;

    // Attach progress and completed handlers to any existing tasks.
    auto allTasks{ Windows::ApplicationModel::Background::BackgroundTaskRegistration::AllTasks() };

    for (auto const& task : allTasks)
    {
        if (task.Value().Name() == SampleBackgroundTaskName)
        {
            AttachProgressAndCompletedHandlers(task.Value());
            break;
        }
    }

    UpdateUI();
}
void SampleBackgroundTask::OnNavigatedTo(NavigationEventArgs^ e)
{
    // A pointer back to the main page.  This is needed if you want to call methods in MainPage such
    // as NotifyUser().
    rootPage = MainPage::Current;

    // Attach progress and completed handlers to any existing tasks.
    auto iter = BackgroundTaskRegistration::AllTasks->First();
    auto hascur = iter->HasCurrent;
    while (hascur)
    {
        auto cur = iter->Current->Value;

        if (cur->Name == SampleBackgroundTaskName)
        {
            AttachProgressAndCompletedHandlers(cur);
            break;
        }

        hascur = iter->MoveNext();
    }

    UpdateUI();
}