Trying to access WPF Controls from another thread is leading into 'System.InvalidOperationException' (cross thread access violation). The Description of the exception says, that the accessed object is not owned by the calling thread.
The following code shows that the 'System.InvalidOperationException' is not thrown when the second thread is accessing an non WPF-Control Object. But Why ?
How can I identify which Object is owned by which thread to avoid this exception ?
namespace Threading {
public class TestObject {
public Object Data { get; set; }
}
public partial class MainWindow : Window {
TestObject _toOwnedByUI;
TextBox _txtOwnedByUI;
BackgroundWorker _bw;
public MainWindow () {
InitializeComponent ();
_bw = new BackgroundWorker ();
_txtOwnedByUI = OutputBox;
_bw.DoWork += onBwDoWork;
}
private void Button_Click (object sender, RoutedEventArgs e) {
// initvalues from UI-Thread
_toOwnedByUI = new TestObject () { Data = "UI Thread INIT" };
_txtOwnedByUI.Text = "UI Thread INIT";
// Start Second Thread
_bw.RunWorkerAsync ();
}
// -------------------------------------------------------------------------
private void onBwDoWork(Object Sender, DoWorkEventArgs e) {
// Change Values of testobjects by Second Thread
_toOwnedByUI.Data = "Changed by BW-Thread";
_txtOwnedByUI.Text = "Changed by BW-Thread"; // <----- throws System.InvalidOperationException : Invalid Thread
}
}
}