The calling thread cannot access this object because a different thread owns it.WPF

后端 未结 6 834
一向
一向 2020-11-28 10:16

Whenever I refresh a label, I got this error: The calling thread cannot access this object because a different thread owns it. I tried to invoke b

6条回答
  •  臣服心动
    2020-11-28 10:29

    I started one non-UI Thread and within this thread I stared one UI thread too. So my requirement is like running an UI thread within a non-UI thread. When handling this scenario I got the following exception. "Exception: The calling thread cannot access this object because a different thread owns it."

    In this case I used the Dispatcher.Invoke method of the UI element as follows and it worked well.

    if (m_contextWindow == null)
    {   
        System.Threading.Thread newWindowThread = new System.Threading.Thread(new ThreadStart( () =>
        {
            // Create and show the Window
            m_contextWindow = new ContextWindow();
            m_contextWindow.DataContext = this;                            
            m_contextWindow.Show();
            // Start the Dispatcher Processing
            System.Windows.Threading.Dispatcher.Run();
        }));
    
        // Set the apartment state
        newWindowThread.SetApartmentState(ApartmentState.STA);
        // Make the thread a background thread
        newWindowThread.IsBackground = true;
        // Start the thread
        newWindowThread.Start();
    }
    else
    {                     
        this.m_contextWindow.Dispatcher.Invoke(new ThreadStart(() => 
        {
            m_contextWindow.DataContext = this;
            if (m_contextWindow.Visibility == System.Windows.Visibility.Collapsed
             || m_contextWindow.Visibility == System.Windows.Visibility.Hidden)
                m_contextWindow.Visibility = System.Windows.Visibility.Visible;
        }));                            
    }
    

提交回复
热议问题