Threaded Bindings don't update

M

Marc Gravell

In the following example, the Bindings don't update the UI if the property
change is triggered from the non-UI thread - see the async button - from the
listbox contents (and observation) the change to the object has occurred
correctly; have I got a foobar somewhere, or is this the expected behaviour?
I can "fix" it by adding an additional few lines (follows main code), but
this is ugly; any ideas? And can I get a robust MVP-style UI in a threaded
environment using this binding approach?

Marc

===

using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
namespace TestApp {
static class Program {
[STAThread]
static void Main() {
SomeClass obj = new SomeClass();
using (Form f = new Form())
using(TextBox tb1 = new TextBox())
using (TextBox tb2 = new TextBox())
using (TextBox tb3 = new TextBox())
using (BindingSource bs = new BindingSource())
using (Button cycleSyncButton = new Button())
using (ListBox lb = new ListBox())
using (Button cycleAsyncButton = new Button()) {
// debug ougput:
obj.PropertyChanged += delegate(object sender,
PropertyChangedEventArgs args) {
lb.BeginInvoke((ThreadStart)delegate { // list property
changes
string message =
string.Format("{0}={1}",args.PropertyName,sender.GetType().GetProperty(args.PropertyName).GetValue(sender,null));
lb.Items.Insert(0, message);
});
}; // end debug ougput:

cycleSyncButton.Click += delegate { obj.Cycle(); };
cycleAsyncButton.Click += delegate {
ThreadPool.QueueUserWorkItem(delegate { obj.Cycle(); }); };
tb1.Dock = tb2.Dock = tb3.Dock = cycleSyncButton.Dock =
cycleAsyncButton.Dock = DockStyle.Top;
lb.Dock = DockStyle.Fill;
cycleAsyncButton.Text = "Cycle Async";
cycleSyncButton.Text = "Cycle Sync";
bs.DataSource = typeof(SomeClass);
tb1.DataBindings.Add(new Binding("Text", bs, "Prop1",
true));
tb2.DataBindings.Add(new Binding("Text", bs, "Prop2",
true));
tb3.DataBindings.Add(new Binding("Text", bs, "Prop3",
true));
f.Controls.AddRange(new Control[] {lb, cycleAsyncButton,
cycleSyncButton, tb3, tb2, tb1 });
List<SomeClass> data = new List<SomeClass>();
data.Add(obj);
bs.DataSource = data;
f.ShowDialog();
}
}
}
sealed class SomeClass : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new
PropertyChangedEventArgs(propertyName));
}
private string _prop1 = "val1", _prop2 = "val2", _prop3 = "val3";
public string Prop1 {
get { return _prop1; }
set { if (_prop1 != value) { _prop1 = value;
OnPropertyChanged("Prop1"); } }
}
public string Prop2 {
get { return _prop2; }
set { if (_prop2 != value) { _prop2 = value;
OnPropertyChanged("Prop2"); } }
}
public string Prop3 {
get { return _prop3; }
set { if (_prop3 != value) { _prop3 = value;
OnPropertyChanged("Prop3"); } }
}
public void Cycle() {
string temp = Prop1;
Prop1 = Prop2;
Prop2 = Prop3;
Prop3 = temp;
}
}
}

===

additional fixup lines (just after existing PropertyChanged +=):
obj.PropertyChanged += delegate(object sender, PropertyChangedEventArgs
args) {
if (ReferenceEquals(sender, bs.Current) && f.InvokeRequired) {
f.BeginInvoke((ThreadStart)delegate {
bs.ResetCurrentItem();
});
};
};
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi

If you are updating the UI from another thread you need to use
Control.Invoke, there is no way around it


--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Marc Gravell said:
In the following example, the Bindings don't update the UI if the property
change is triggered from the non-UI thread - see the async button - from
the listbox contents (and observation) the change to the object has
occurred correctly; have I got a foobar somewhere, or is this the expected
behaviour? I can "fix" it by adding an additional few lines (follows main
code), but this is ugly; any ideas? And can I get a robust MVP-style UI in
a threaded environment using this binding approach?

Marc

===

using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
namespace TestApp {
static class Program {
[STAThread]
static void Main() {
SomeClass obj = new SomeClass();
using (Form f = new Form())
using(TextBox tb1 = new TextBox())
using (TextBox tb2 = new TextBox())
using (TextBox tb3 = new TextBox())
using (BindingSource bs = new BindingSource())
using (Button cycleSyncButton = new Button())
using (ListBox lb = new ListBox())
using (Button cycleAsyncButton = new Button()) {
// debug ougput:
obj.PropertyChanged += delegate(object sender,
PropertyChangedEventArgs args) {
lb.BeginInvoke((ThreadStart)delegate { // list
property changes
string message =
string.Format("{0}={1}",args.PropertyName,sender.GetType().GetProperty(args.PropertyName).GetValue(sender,null));
lb.Items.Insert(0, message);
});
}; // end debug ougput:

cycleSyncButton.Click += delegate { obj.Cycle(); };
cycleAsyncButton.Click += delegate {
ThreadPool.QueueUserWorkItem(delegate { obj.Cycle(); }); };
tb1.Dock = tb2.Dock = tb3.Dock = cycleSyncButton.Dock =
cycleAsyncButton.Dock = DockStyle.Top;
lb.Dock = DockStyle.Fill;
cycleAsyncButton.Text = "Cycle Async";
cycleSyncButton.Text = "Cycle Sync";
bs.DataSource = typeof(SomeClass);
tb1.DataBindings.Add(new Binding("Text", bs, "Prop1",
true));
tb2.DataBindings.Add(new Binding("Text", bs, "Prop2",
true));
tb3.DataBindings.Add(new Binding("Text", bs, "Prop3",
true));
f.Controls.AddRange(new Control[] {lb, cycleAsyncButton,
cycleSyncButton, tb3, tb2, tb1 });
List<SomeClass> data = new List<SomeClass>();
data.Add(obj);
bs.DataSource = data;
f.ShowDialog();
}
}
}
sealed class SomeClass : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new
PropertyChangedEventArgs(propertyName));
}
private string _prop1 = "val1", _prop2 = "val2", _prop3 = "val3";
public string Prop1 {
get { return _prop1; }
set { if (_prop1 != value) { _prop1 = value;
OnPropertyChanged("Prop1"); } }
}
public string Prop2 {
get { return _prop2; }
set { if (_prop2 != value) { _prop2 = value;
OnPropertyChanged("Prop2"); } }
}
public string Prop3 {
get { return _prop3; }
set { if (_prop3 != value) { _prop3 = value;
OnPropertyChanged("Prop3"); } }
}
public void Cycle() {
string temp = Prop1;
Prop1 = Prop2;
Prop2 = Prop3;
Prop3 = temp;
}
}
}

===

additional fixup lines (just after existing PropertyChanged +=):
obj.PropertyChanged += delegate(object sender, PropertyChangedEventArgs
args) {
if (ReferenceEquals(sender, bs.Current) && f.InvokeRequired) {
f.BeginInvoke((ThreadStart)delegate {
bs.ResetCurrentItem();
});
};
};
 
M

Marc Gravell

No; **I'm** not updating the UI **at all**; I am updating the object model;
the point is that I would quite like my UI to update itself. In a disparate
application with multiple forms and threads, at the point of doing the
object model I have no business knowing what views in the UI are based on my
object model - I just want them to update themselves in response to the
property change notification. Does that make sense?

Marc

Ignacio Machin ( .NET/ C# MVP ) said:
Hi

If you are updating the UI from another thread you need to use
Control.Invoke, there is no way around it


--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Marc Gravell said:
In the following example, the Bindings don't update the UI if the
property change is triggered from the non-UI thread - see the async
button - from the listbox contents (and observation) the change to the
object has occurred correctly; have I got a foobar somewhere, or is this
the expected behaviour? I can "fix" it by adding an additional few lines
(follows main code), but this is ugly; any ideas? And can I get a robust
MVP-style UI in a threaded environment using this binding approach?

Marc

===

using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
namespace TestApp {
static class Program {
[STAThread]
static void Main() {
SomeClass obj = new SomeClass();
using (Form f = new Form())
using(TextBox tb1 = new TextBox())
using (TextBox tb2 = new TextBox())
using (TextBox tb3 = new TextBox())
using (BindingSource bs = new BindingSource())
using (Button cycleSyncButton = new Button())
using (ListBox lb = new ListBox())
using (Button cycleAsyncButton = new Button()) {
// debug ougput:
obj.PropertyChanged += delegate(object sender,
PropertyChangedEventArgs args) {
lb.BeginInvoke((ThreadStart)delegate { // list
property changes
string message =
string.Format("{0}={1}",args.PropertyName,sender.GetType().GetProperty(args.PropertyName).GetValue(sender,null));
lb.Items.Insert(0, message);
});
}; // end debug ougput:

cycleSyncButton.Click += delegate { obj.Cycle(); };
cycleAsyncButton.Click += delegate {
ThreadPool.QueueUserWorkItem(delegate { obj.Cycle(); }); };
tb1.Dock = tb2.Dock = tb3.Dock = cycleSyncButton.Dock =
cycleAsyncButton.Dock = DockStyle.Top;
lb.Dock = DockStyle.Fill;
cycleAsyncButton.Text = "Cycle Async";
cycleSyncButton.Text = "Cycle Sync";
bs.DataSource = typeof(SomeClass);
tb1.DataBindings.Add(new Binding("Text", bs, "Prop1",
true));
tb2.DataBindings.Add(new Binding("Text", bs, "Prop2",
true));
tb3.DataBindings.Add(new Binding("Text", bs, "Prop3",
true));
f.Controls.AddRange(new Control[] {lb, cycleAsyncButton,
cycleSyncButton, tb3, tb2, tb1 });
List<SomeClass> data = new List<SomeClass>();
data.Add(obj);
bs.DataSource = data;
f.ShowDialog();
}
}
}
sealed class SomeClass : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new
PropertyChangedEventArgs(propertyName));
}
private string _prop1 = "val1", _prop2 = "val2", _prop3 = "val3";
public string Prop1 {
get { return _prop1; }
set { if (_prop1 != value) { _prop1 = value;
OnPropertyChanged("Prop1"); } }
}
public string Prop2 {
get { return _prop2; }
set { if (_prop2 != value) { _prop2 = value;
OnPropertyChanged("Prop2"); } }
}
public string Prop3 {
get { return _prop3; }
set { if (_prop3 != value) { _prop3 = value;
OnPropertyChanged("Prop3"); } }
}
public void Cycle() {
string temp = Prop1;
Prop1 = Prop2;
Prop2 = Prop3;
Prop3 = temp;
}
}
}

===

additional fixup lines (just after existing PropertyChanged +=):
obj.PropertyChanged += delegate(object sender, PropertyChangedEventArgs
args) {
if (ReferenceEquals(sender, bs.Current) && f.InvokeRequired) {
f.BeginInvoke((ThreadStart)delegate {
bs.ResetCurrentItem();
});
};
};
 
N

Nicholas Paldino [.NET/C# MVP]

Marc,

It does make sense, however, you have a coupling between the change that
occurs in your object, and the UI. Since that change happens on another
thread, you have to marshal that call to the proper thread to update the UI.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Marc Gravell said:
No; **I'm** not updating the UI **at all**; I am updating the object
model; the point is that I would quite like my UI to update itself. In a
disparate application with multiple forms and threads, at the point of
doing the object model I have no business knowing what views in the UI are
based on my object model - I just want them to update themselves in
response to the property change notification. Does that make sense?

Marc

Ignacio Machin ( .NET/ C# MVP ) said:
Hi

If you are updating the UI from another thread you need to use
Control.Invoke, there is no way around it


--
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

Marc Gravell said:
In the following example, the Bindings don't update the UI if the
property change is triggered from the non-UI thread - see the async
button - from the listbox contents (and observation) the change to the
object has occurred correctly; have I got a foobar somewhere, or is this
the expected behaviour? I can "fix" it by adding an additional few lines
(follows main code), but this is ugly; any ideas? And can I get a robust
MVP-style UI in a threaded environment using this binding approach?

Marc

===

using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
namespace TestApp {
static class Program {
[STAThread]
static void Main() {
SomeClass obj = new SomeClass();
using (Form f = new Form())
using(TextBox tb1 = new TextBox())
using (TextBox tb2 = new TextBox())
using (TextBox tb3 = new TextBox())
using (BindingSource bs = new BindingSource())
using (Button cycleSyncButton = new Button())
using (ListBox lb = new ListBox())
using (Button cycleAsyncButton = new Button()) {
// debug ougput:
obj.PropertyChanged += delegate(object sender,
PropertyChangedEventArgs args) {
lb.BeginInvoke((ThreadStart)delegate { // list
property changes
string message =
string.Format("{0}={1}",args.PropertyName,sender.GetType().GetProperty(args.PropertyName).GetValue(sender,null));
lb.Items.Insert(0, message);
});
}; // end debug ougput:

cycleSyncButton.Click += delegate { obj.Cycle(); };
cycleAsyncButton.Click += delegate {
ThreadPool.QueueUserWorkItem(delegate { obj.Cycle(); }); };
tb1.Dock = tb2.Dock = tb3.Dock = cycleSyncButton.Dock =
cycleAsyncButton.Dock = DockStyle.Top;
lb.Dock = DockStyle.Fill;
cycleAsyncButton.Text = "Cycle Async";
cycleSyncButton.Text = "Cycle Sync";
bs.DataSource = typeof(SomeClass);
tb1.DataBindings.Add(new Binding("Text", bs, "Prop1",
true));
tb2.DataBindings.Add(new Binding("Text", bs, "Prop2",
true));
tb3.DataBindings.Add(new Binding("Text", bs, "Prop3",
true));
f.Controls.AddRange(new Control[] {lb, cycleAsyncButton,
cycleSyncButton, tb3, tb2, tb1 });
List<SomeClass> data = new List<SomeClass>();
data.Add(obj);
bs.DataSource = data;
f.ShowDialog();
}
}
}
sealed class SomeClass : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName) {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new
PropertyChangedEventArgs(propertyName));
}
private string _prop1 = "val1", _prop2 = "val2", _prop3 = "val3";
public string Prop1 {
get { return _prop1; }
set { if (_prop1 != value) { _prop1 = value;
OnPropertyChanged("Prop1"); } }
}
public string Prop2 {
get { return _prop2; }
set { if (_prop2 != value) { _prop2 = value;
OnPropertyChanged("Prop2"); } }
}
public string Prop3 {
get { return _prop3; }
set { if (_prop3 != value) { _prop3 = value;
OnPropertyChanged("Prop3"); } }
}
public void Cycle() {
string temp = Prop1;
Prop1 = Prop2;
Prop2 = Prop3;
Prop3 = temp;
}
}
}

===

additional fixup lines (just after existing PropertyChanged +=):
obj.PropertyChanged += delegate(object sender, PropertyChangedEventArgs
args) {
if (ReferenceEquals(sender, bs.Current) && f.InvokeRequired) {
f.BeginInvoke((ThreadStart)delegate {
bs.ResetCurrentItem();
});
};
};
 
M

Marc Gravell

OK; allow me to clarify. I'm trying to implement an MVP-style UI, where any
part of the system has no real knowledge about what other aspects may be
monitoring [&V] the data [&M]. Particularly for intensive operations,
processing may occur on backgound threads (i.e. a pool thread) - however,
this has no clue whatsoever about what UI thread(s) are displaying what
form(s) etc, so cannot proactively marshal. I just want the data-model to
notify the UI "I've changed", and the UI to update itself accordingly
(marshalling itself). This *feels* a common enough pattern - am I being
obscure? I kinda expected that Bindings would deal with this themselves -
after all, what's the point of them only responding to changes on their own
thread in a runtime that supports full-blooded threading? Surely the Binding
class could (should?) internally spot that it is talking to a UI control and
use Invoke to marshal? Otherwise it is missing updates...
I guess I can either or roll my own, either by additional handling of the
event (as example) or, by providing access to an ISynchronizeInvoke handle.
But does anything that would handle this already exist?

Marc
 
M

Marc Gravell

Et voila; one x-thread compatible Binding implementation...

Hope this helps somebody out there; feel free to tear it apart if I'm "off
on one"... Actually, most of this code is just ctor-forwarding! Shame MS
didn't build it in by default...

Marc

public class ThreadedBinding : Binding {
// ctors to match Binding
public ThreadedBinding(string propertyName, object dataSource,
string dataMember)
: base(propertyName, dataSource, dataMember) {
}
public ThreadedBinding(string propertyName, object dataSource,
string dataMember, bool formattingEnabled)
: base(propertyName, dataSource, dataMember, formattingEnabled)
{
}
public ThreadedBinding(string propertyName, object dataSource,
string dataMember, bool formattingEnabled, DataSourceUpdateMode
dataSourceUpdateMode)
: base(propertyName, dataSource, dataMember, formattingEnabled,
dataSourceUpdateMode) {
}
public ThreadedBinding(string propertyName, object dataSource,
string dataMember, bool formattingEnabled, DataSourceUpdateMode
dataSourceUpdateMode, object nullValue)
: base(propertyName, dataSource, dataMember, formattingEnabled,
dataSourceUpdateMode, nullValue) {
}
public ThreadedBinding(string propertyName, object dataSource,
string dataMember, bool formattingEnabled, DataSourceUpdateMode
dataSourceUpdateMode, object nullValue, string formatString)
: base(propertyName, dataSource, dataMember, formattingEnabled,
dataSourceUpdateMode, nullValue, formatString) {
}
public ThreadedBinding(string propertyName, object dataSource,
string dataMember, bool formattingEnabled, DataSourceUpdateMode
dataSourceUpdateMode, object nullValue, string formatString, IFormatProvider
formatInfo)
: base(propertyName, dataSource, dataMember, formattingEnabled,
dataSourceUpdateMode, nullValue, formatString, formatInfo) {
}
// main purpose; detect x-thread operations and compensate
protected override void OnBindingComplete(BindingCompleteEventArgs
e) {
base.OnBindingComplete(e);
if (e.BindingCompleteContext ==
BindingCompleteContext.ControlUpdate
&& e.BindingCompleteState == BindingCompleteState.Exception
&& e.Exception is InvalidOperationException) {
if (Control != null && Control.InvokeRequired) {
Control.BeginInvoke(new MethodInvoker(ReadValue));
}
}
}
}
 
D

davet

I am having exactly the same problem on a WinForms project I am working on using the Compact Framework.

I have a class which implements INotifyPropertyChanged but causes an exception every time a binding is updated from a background thread.

I saw this code and thought it would solve all my problems... however I am still getting an exception BEFORE OnBindingComplete is called. The exception just reports: "Control.Invoke must be used to interact with controls created on a separate thread."... which I already know.

I can't believe this isn't handled by the framework! Anyone have any suggestions? Thanks.
 
D

davet

A bit more information... OnFormat is called successfully before the above exception occurs.
 
D

davet

You saw which code? You didn't quote anything and you are replying to a

discussion that is so old, it's not even in my newsreader history any

longer.



If you want help, you have to post the relevant code. The best question

will include a concise-but-complete code example that reliably reproduces

the problem.



In the meantime, there's nothing in your question that suggests that

there's anything wrong here except for you failing to comply with the

requirements of the framework. The exception message is clear, and you

state that you already know about what's it's instructing you to do.



Wishing the framework didn't have this requirement, or being incredulous

that it does, does nothing to get your code to work. Whether you can

believe the requirement exists or not, as long as it does your code will

have to accommodate it.



If you stop accessing the control object from a thread other than the one

that owns it, everything will likely be fine. So just do that.



Pete


Hi Pete, thanks for the reply. Here is the post I was referring to, I am aware it is very old, but it is still relevant today:

Et voila; one x-thread compatible Binding implementation...
Hope this helps somebody out there; feel free to tear it apart if I'm "off
on one"... Actually, most of this code is just ctor-forwarding! Shame MS
didn't build it in by default...

Marc

public class ThreadedBinding : Binding {
// ctors to match Binding
public ThreadedBinding(string propertyName, object dataSource,
string dataMember)
: base(propertyName, dataSource, dataMember) {
}
public ThreadedBinding(string propertyName, object dataSource,
string dataMember, bool formattingEnabled)
: base(propertyName, dataSource, dataMember, formattingEnabled)
{
}
public ThreadedBinding(string propertyName, object dataSource,
string dataMember, bool formattingEnabled, DataSourceUpdateMode
dataSourceUpdateMode)
: base(propertyName, dataSource, dataMember, formattingEnabled,
dataSourceUpdateMode) {
}
public ThreadedBinding(string propertyName, object dataSource,
string dataMember, bool formattingEnabled, DataSourceUpdateMode
dataSourceUpdateMode, object nullValue)
: base(propertyName, dataSource, dataMember, formattingEnabled,
dataSourceUpdateMode, nullValue) {
}
public ThreadedBinding(string propertyName, object dataSource,
string dataMember, bool formattingEnabled, DataSourceUpdateMode
dataSourceUpdateMode, object nullValue, string formatString)
: base(propertyName, dataSource, dataMember, formattingEnabled,
dataSourceUpdateMode, nullValue, formatString) {
}
public ThreadedBinding(string propertyName, object dataSource,
string dataMember, bool formattingEnabled, DataSourceUpdateMode
dataSourceUpdateMode, object nullValue, string formatString, IFormatProvider
formatInfo)
: base(propertyName, dataSource, dataMember, formattingEnabled,
dataSourceUpdateMode, nullValue, formatString, formatInfo) {
}
// main purpose; detect x-thread operations and compensate
protected override void OnBindingComplete(BindingCompleteEventArgs
e) {
base.OnBindingComplete(e);
if (e.BindingCompleteContext ==
BindingCompleteContext.ControlUpdate
&& e.BindingCompleteState == BindingCompleteState.Exception
&& e.Exception is InvalidOperationException) {
if (Control != null && Control.InvokeRequired) {
Control.BeginInvoke(new MethodInvoker(ReadValue));
}
}
}
}


On the face if it, this seems to make a lot of sense. But, you're right, I can't sit here complaining about the framework so I have a work-around. It would just be nice to use the above class and do things "properly".
 
Top