0

在我的项目中,我有文本框,当事件触发时,_rtpAudioChannel_ChannelStateChanged 我得到了这个异常调用线程无法访问这个对象,因为另一个线程拥有它

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


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

4 回答 4

1

最终解决方案:为此寻找了几个小时..您可以从任何地方调用 SetMSG(text) 函数。它会将 StatTextBox.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;
    }  
于 2012-11-11T14:29:51.437 回答
1

由于技术原因,在一个线程中创建的窗口和控件不能从任何其他线程访问。要解决该问题,您必须将控制访问操作(获取和设置Text)“转发”到适当的线程,在 WPF 中称为调度程序线程

通过调用StatTextBox.Dispatcher.Invoke(这是同步的,即在处理完成之前不返回)或StatTextBox.Dispatcher.BeginInvoke(这是异步的并提供更好的性能)来做到这一点。

于 2012-08-01T07:52:31.720 回答
0

如果您使用 Windows 窗体,您应该从创建控件的同一线程访问窗口控件或使用编组。

您可以在代码中使用此变体:

var lambda = () => StatTextBox.Text = "some text here" + "\n" + StatTextBox.Text;
if (StatTextBox.InvokeRequired)
{
    control.Invoke(lambda, new object[0]);
}
else
{
    lambda();
}
于 2012-08-01T07:58:02.517 回答
0

尝试这个:

    StatTextBox.Invoke((MethodInvoker)delegate()
    {
        StatTextBox.Text = "some text here" + "\n" + StatTextBox.Text;
    }
于 2012-08-01T07:51:00.597 回答