如果计时器停止运行或UI重新加载c ++ winrt,后台线程会发生什么

问题描述 投票:0回答:1

我有一些计时器成员:

Windows::UI::Xaml::DispatcherTimer^ m_pollingTimer;

我如下创建计时器,并在计时器勾选时执行一些异步任务:

m_pollingTimer = CreateAndStartDispatcherTimer(500ms, &MainPage::OnPollingTick);

当重新加载/挂起应用程序时,我如下停止计时器:

停止所有计时器:

for (auto timer : {m_pollingTimer})
{
    if (timer)
        timer->Stop();
}

如果我停止计时器本身,后台任务会怎样?-它是否也停止后台任务或等待任务完成?

重新加载应用程序:

bool MainPage::Reload(Platform::Object^ param)
{
    auto rootFrame = dynamic_cast<Windows::UI::Xaml::Controls::Frame^>(Window::Current->Content);

    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (rootFrame == nullptr)
    {
        // Create a Frame to act as the navigation context and associate it with
        // a SuspensionManager key
        rootFrame = ref new Windows::UI::Xaml::Controls::Frame();
    }

    auto type = rootFrame->CurrentSourcePageType;

    try
    {
        return rootFrame->Navigate(type, param);
    }
    catch (Platform::Exception^ ex)
    {
        throw ex;
    }
}

停止计时器后,我重新加载了UI。

后台线程将继续运行还是已停止?

winrt-xaml c++-cx
1个回答
0
投票

[如果您有要在挂起应用程序之前完成的工作,则应在完成背景工作后,在take a Deferral上单击Deferral,然后在Suspending event上单击Suspending

这可确保您不会在后台线程工作中途冻结它,然后稍后再次唤醒它,同时运行重新加载代码。那很容易造成比赛条件。另外,您的后台工作还应定期进行轮询,以查看是否有待中止,因此应尽早终止。

© www.soinside.com 2019 - 2024. All rights reserved.