Note: Forums will be making significant UX changes to address key usability improvements surrounding search, discoverability and navigation. To learn more about these changes please visit the announcement which can be found HERE.
The calling thread cannot access this object because a different thread owns it error pops up ?

Locked The calling thread cannot access this object because a different thread owns it error pops up ?

  • Tuesday, April 03, 2012 6:44 AM
     
     

    Here is my method which is showing the error.If i am not using the thread it will works fine, how to use it with the help of threading.

    public void Mthread()
            {
                string s;            
                SpeechSynthesizer ss = new SpeechSynthesizer();
                s = textBox1.Text;   //Here it is showing the error.
                ss.Speak(s);
               
            }

    private void button2_Click(object sender, RoutedEventArgs e)
            {
                Thread th = new Thread(Mthread);
                th.Start();
                
            }


    MSDN Forum

All Replies

  • Thursday, April 05, 2012 2:53 AM
    Moderator
     
     Answered

    Hi,

    This is because UI thread owned the textBox1, we can't use it directly in another thread. You can adjust the following code to fit your requirement:

    public void Mthread()
            {
                string s;           
                SpeechSynthesizer ss = new SpeechSynthesizer();
                textBox1.Dispatcher.Invoke(DispatcherPriority.Normal,
                    (SendOrPostCallback)delegate
                    {                                      
                        s = textBox1.Text;                   
                    },
                    null);           

                 ss.Speak(s);           
            }

    Thanks.


    Leo Tang [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked As Answer by Amal E S Monday, April 09, 2012 6:10 AM
    •  
  • Monday, April 09, 2012 6:04 AM
     
     

    Hello LeoTang

    It works ,  Thanks a lot

    But i think we have  to declare the string s to global , why we have to declare it as globlal ?




    • Edited by Amal E S Monday, April 09, 2012 6:11 AM
    •