繁体   English   中英

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

[英]What happens to background thread if timers are stopped or UI is reloaded c++ winrt

我有一些计时器作为成员:

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。

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

现有线程将使用应用程序的 rest 暂停。 如评论中所述,不会引发新的计时器事件,因为您手动在它们上调用了Stop

如果您有工作要在应用程序暂停之前完成,您应该对Suspending事件进行Deferral ,然后仅在后台工作完成后Complete

这可确保您不会在其工作中途冻结后台线程,然后在稍后再次唤醒它同时运行您的重新加载代码。 这很容易导致竞争条件。 此外,您的后台工作应定期轮询以查看是否暂停挂起,因此应尝试提前终止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM