【问题标题】:What happens to background thread if timers are stopped or UI is reloaded c++ winrt如果计时器停止或重新加载 UI,后台线程会发生什么情况 c++ winrt
【发布时间】:2020-03-14 13:06:20
【问题描述】:

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

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。

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

【问题讨论】:

  • 当计时器停止时,不会引发启动新后台操作的新事件 - 但在后台线程中运行的任何代码仍将运行直到完成。您正在运行哪些类型的后台任务?
  • 并发::任务 pplwin。我正在从仅在应用程序启动/重新启动时初始化的 const 方法访问一些成员。我不确定我是否是线程安全的!
  • const-正确的 C++ 代码自动线程安全提供没有其他代码正在改变 const 方法正在读取的状态/内存(@ 987654321@)。如果成员只在启动期间被修改,那么它将是线程安全的,没有什么可担心的。
  • for (auto timer : {m_pollingTimer}) - 我很好奇你为什么使用这种模式?

标签: winrt-xaml c++-cx


【解决方案1】:

现有线程将与应用程序的其余部分一起暂停。如 cmets 中所述,不会引发新的计时器事件,因为您手动调用了它们的 Stop

如果您有要在应用暂停之前完成的工作,您应该在 Suspending eventtake a Deferral,然后在后台工作完成后仅在 Complete it 上完成。

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

【讨论】:

    猜你喜欢
    • 2014-11-12
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    相关资源
    最近更新 更多