Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is WPF data binding thread safe?

If a property value is updated from worker thread (non UI), will it reflect in control that is using data-binding and listening to property change?

Thanks for your interest.

like image 334
Manish Basantani Avatar asked Feb 23 '23 10:02

Manish Basantani


1 Answers

WPF is using Dispatcher, so that everything is working on one UI thread, but have switch type concurrency. And when you update some prop of dependency object, it actually post a new job onto dispatcher queue. When that job runs, it runs on the UI thread and updates controls properly. But if you try to access controls directly from background thread you will get an exception.

There are certains edge cases because of this implementation. E.g. even if you update the prop on UI thread, you can't expect that control will synchronously update it self to reflect you changes. So, if you have xaml like this:

<TextBox x:name="tb" Text="{Binding Text"}/>

And code like this:

var model = new { Text = "aaa" };
tb.DataContext = model;
model.Text = "bbb";
Debug.Assert(tb.Text == "bbb");

Assertion may fail, because the update may go via dispatcher in the next task. And it will not be updated, until this current call is ended and control is returned to dispatcher.

like image 166
Vladimir Perevalov Avatar answered Feb 25 '23 00:02

Vladimir Perevalov