是否可以在通过std :: thread创建的线程下访问XAML控件TextBlock?

时间:2019-05-10 15:17:16

标签: c++ multithreading xaml windows-runtime access

我有一个带有函数 _tproc(p)的C ++ / WinRT XAML程序,其中p简称为 MainPage * p

编译过程可以,但是如果通过std :: thread创建进行调用则失败。

这是源代码:

MainPage.H

struct MainPage : MainPageT<MainPage>
{
    TextBlock           m_tbx;
    TranslateTransform  m_pos;
    int                 m_x;
    int                 m_y;
    int                 m_itest;

    MainPage();
    int32_t MyProperty  ();
    void    MyProperty  (int32_t value); 
    int     f_iOnInit   ();
};

MainPage.cpp

void _tproc ( winrt::WINRT_DEMO::implementation::MainPage* p = nullptr) 
{
    if (p == nullptr) return;
    auto x{ 500 };
    auto y{ 500 };

    // NOTE: Instructions below caused error if _tproc() is 
    //       called via std::thread  
    p->m_pos.X(x); 
    p->m_pos.Y(y); 
    p->m_tbx.RenderTransform(p->m_pos); 
}

MainPage::MainPage()
{
    InitializeComponent();
    f_iOnInit();
}

int32_t MainPage::MyProperty()
{
    throw hresult_not_implemented();
}

void MainPage::MyProperty(int32_t /* value */)
{
    throw hresult_not_implemented();
}

int MainPage::f_iOnInit ()
{
    m_tbx.FontFamily( Windows::UI::Xaml::Media::FontFamily( L"Segoe UI Semibold" ) );
    m_tbx.FontSize(24.0);
    m_tbx.Foreground( SolidColorBrush( Colors::Orange() ) );
    m_tbx.VerticalAlignment( VerticalAlignment::Center );
    m_tbx.HorizontalAlignment( HorizontalAlignment::Center );
    m_tbx.TextAlignment( TextAlignment::Left );              
    m_tbx.Text( L"Hello World!" );

    this->Content().as<Panel>().Children().Append( m_tbx );

    // Calling _tproc() below is fine.
    //_tproc( this ); 

    // Error occurred, explained within _tproc()
    std::thread t( _tproc, this ); 
    t.join();

    return 0;
}

作为参考,捕获运行时错误页面HERE

请告知。

0 个答案:

没有答案