473,395 Members | 1,653 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Threaded Bindings don't update

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.G etType().GetProperty(args.PropertyName).GetValue(s ender,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<SomeClassdata = 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();
});
};
};
Jul 24 '06 #1
5 3835
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" <ma**********@gmail.comwrote in message
news:%2***************@TK2MSFTNGP05.phx.gbl...
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.G etType().GetProperty(args.PropertyName).GetValue(s ender,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<SomeClassdata = 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();
});
};
};

Jul 24 '06 #2
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 )" <ignacio.machin AT dot.state.fl.uswrote
in message news:OW*************@TK2MSFTNGP02.phx.gbl...
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" <ma**********@gmail.comwrote in message
news:%2***************@TK2MSFTNGP05.phx.gbl...
>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<SomeClassdata = 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();
});
};
};


Jul 24 '06 #3
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]
- mv*@spam.guard.caspershouse.com

"Marc Gravell" <ma**********@gmail.comwrote in message
news:O9*************@TK2MSFTNGP05.phx.gbl...
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 )" <ignacio.machin AT dot.state.fl.us>
wrote in message news:OW*************@TK2MSFTNGP02.phx.gbl...
>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" <ma**********@gmail.comwrote in message
news:%2***************@TK2MSFTNGP05.phx.gbl...
>>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<SomeClassdata = 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();
});
};
};



Jul 24 '06 #4
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
Jul 25 '06 #5
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));
}
}
}
}
Jul 25 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Mike Rovner | last post by:
Hello, Please advise on multi-threaded list *append*: import time, random, thread aList = def main(): for i in range(10):
1
by: Arthur Chereau | last post by:
Hi, I'm trying to setup viewcvs to work with subversion 1.2.0 on Linux with Python 2.4.1. The last viewcvs (from CVS) needs subversion python bindings. I installed swig and built subversion from...
0
by: Neo | last post by:
I was wondering what is the "right" way to deal with datasets is. Particularly sharing DataSets between forms. Here is my situation. I have a simple Customer Database, that holds some information...
0
by: Stuart Norris | last post by:
Dear Group, I am attempting to write a "splash" and "status" Form using a second thread. I wish to use this Form to display status information to the user when I do CPU intensive work in my...
2
by: Steve Stover | last post by:
I want to use the caching API in .net to store data. The data would be stored in a data table class that has approx. 10 columns and 71 rows. What I need to know is this: According to Microsoft's...
14
by: Ron L | last post by:
All I am working with a DataGrid and a form consisting of a number of text, checkbox, combobox controls, all bound to the same datatable. When I click on my "New" button, I create a new row,...
12
by: Thomas Bartkus | last post by:
Does anyone use emacs together with both WordStar key bindings and python mode? I'm afraid that Wordstar editing key commands are burned R/O into my knuckles! I would like to play with emacs...
1
by: Jason Yamada-Hanff | last post by:
Hi all, I'm working on a project that would benefit very much from Python Freetype2 bindings (the Fonty Python project). I don't want to duplicate efforts and wrap the library again if we don't...
6
by: Leon | last post by:
Hi there, I am trying to use the WebBrowser Control in a form which is being started in an own thread by the main form of my application. Unfortunately I am always getting an error in...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.