I just noticed what I can update binding source from another thread and it just works.
So I prepared a demo below and my questions are:
- Why binding works? Why rising notification from another thread doesn't throws?
- Is it legal to update source from another thread like this?
I was always using and telling to others to use Dispatcher.Invoke
, but maybe I simply don't know something? Maybe binding is always guaranteed to update its target in UI thread or something like this?
<TextBox x:Name="textBox" Text="{Binding Text}" />
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string Text { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
Task.Run(() =>
{
Thread.Sleep(3000); // just wait long enough to ensure window is shown
// works
Text = "123";
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Text)));
// will crash with
// System.InvalidOperationException: 'The calling thread cannot access this object because a different thread owns it'
textBox.Text = "123";
});
}
}