locked
Error setting Text property inside on thread

    Question

  • Hello,


    I'm trying to use one paralel thread to update some properties from XAML components at runtime, and I don’t want to use the Windows.System.Threading.ThreadPool component instead of System.Threading.Thread. I did some tests using C#, and on the line commented below it throw a catastrophic error “Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))”. See on the piece of code bellow.

     

            private void TheadStartButton_Click(object sender, RoutedEventArgs e)

            {

                System.Threading.Thread MyThread = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadMethod));

                System.Threading.Thread.Sleep(2000);

                MyThread.Start();

            }

     

            void ThreadMethod()

            {

                Windows.UI.Popups.MessageDialog BoxOk = new Windows.UI.Popups.MessageDialog("Thread running...");

                BoxOk.ShowAsync().Start();

                //MyTextBlock.Text = "Test...";

            }

     

    Thank you very much for any support.

    Monday, January 02, 2012 1:02 PM

Answers

  • Hi,

    It seems a C# code. Any way, you should use the element in the UI thread and call the element's Dispatcher.Invoke/InvokeAsync to set the "MyTextBloc" property.

            void ThreadMethod()
            {
                Windows.UI.Popups.MessageDialog BoxOk = new Windows.UI.Popups.MessageDialog("Thread running...");
                BoxOk.ShowAsync().Start();
                this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal,
                    (s,e) => { MyTextBlock.Text = "Test..."; }, this, null);
            }
    

    and below is the C++/CX syntax:

        auto callback = ref new InvokedHandler(
            [this](Object^ sender, InvokedHandlerArgs^ eInvoke) { this->MyTextBlock->Text = "Test..."; },
            CallbackContext::Any
            );
        this->Dispatcher->Invoke(CoreDispatcherPriority::Normal, callback, this, nullptr);
    

    Sincerely,


    Bob Bao [MSFT]
    MSDN Community Support | Feedback to us
    • Marked as answer by Leo Soares Tuesday, January 03, 2012 12:58 PM
    Tuesday, January 03, 2012 6:17 AM