Tarek Saied
Tarek Saied

Reputation: 6616

The calling thread cannot access this object because a different thread owns it "exception"

in my project i have text box and when the event fire _rtpAudioChannel_ChannelStateChanged i get this exception The calling thread cannot access this object because a different thread owns it

      void _rtpAudioChannel_ChannelStateChanged(object sender, RtpStateChangedEventArgs<RtpChannelState> e)
      {
            AddNewState("some text here");
      }


      public void AddNewState(string state)
      {
            StatTextBox.Text = state + "\n" + StatTextBox.Text;
      }

Upvotes: 0

Views: 1662

Answers (4)

csomakk
csomakk

Reputation: 5497

the ultimate solution: looked for hours by this.. you can call the SetMSG(text) function from wherever you want. and it will set the StatTextBox.Text to text.

 public void SetMSG(string text){

        if (StatTextBox.Dispatcher.CheckAccess())
        {
            StatTextBox.Text = text;
        }
        else
        {
            SetTextCallback d = new SetTextCallback(SetText);
            StatTextBox.Dispatcher.Invoke(DispatcherPriority.Normal, d, text);
        }
    }
    delegate void SetTextCallBack(string Text);

    public void SetText(string text){
        StatTextBox.Text=text;
    }  

Upvotes: 1

Aleksei Rubanovskii
Aleksei Rubanovskii

Reputation: 11

If you are use windows forms, you shoul access to window control from the same thread, as where the control was created or use marshalling.

You can use this variant in your code:

var lambda = () => StatTextBox.Text = "some text here" + "\n" + StatTextBox.Text;
if (StatTextBox.InvokeRequired)
{
    control.Invoke(lambda, new object[0]);
}
else
{
    lambda();
}

Upvotes: 0

Jon
Jon

Reputation: 437326

For technical reasons, windows and controls created in one thread cannot be accessed from any other thread. To resolve the problem you have to "forward" the control-accessing operation (getting and setting Text) to the appropriate thread, which in WPF is called the dispatcher thread.

Do this by calling StatTextBox.Dispatcher.Invoke (which is synchronous, i.e. does not return until the processing is complete) or StatTextBox.Dispatcher.BeginInvoke (which is asynchronous and offers better performance).

Upvotes: 1

logicnp
logicnp

Reputation: 5836

Try this:

    StatTextBox.Invoke((MethodInvoker)delegate()
    {
        StatTextBox.Text = "some text here" + "\n" + StatTextBox.Text;
    }

Upvotes: 0

Related Questions