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

前端 未结 3 2005
滥情空心
滥情空心 2021-01-12 15:28

In my Windows I have a TextBox which I like to update (text property) from another thread. When doing so, I get the InvalidOperationException (see title). I have found diffe

相关标签:
3条回答
  • 2021-01-12 16:04

    For WPF, I find this construct:

     BackgroundWorker bw = new BackgroundWorker();
      bw.DoWork += ( s, e ) =>
      {
      };
      bw.RunWorkerCompleted += ( s, e ) =>
      {
      };
      bw.RunWorkerAsync();
    

    to be the most useful. The RunWorkerCompleted block will typically update an ObservableCollection or fire off a RaisePropertyChangedEvent.

    0 讨论(0)
  • 2021-01-12 16:14
    Window1.MyWindow.informationTextBox.Dispatcher.Invoke(
        DispatcherPriority.Normal,
        new Action(() => Window1.MyWindow.informationTextBox.Text += value));
    
    0 讨论(0)
  • 2021-01-12 16:23

    Well, using Dispatcher.Invoke or BeginInvoke is definitely the way to go, but you haven't really shown much code other than creating a thread - for example, you haven't started the thread in your second code block.

    If you put the Dispatcher.Invoke code in the place where previously you were getting an InvalidOperationException, it should be fine.

    0 讨论(0)
提交回复
热议问题