Add a delegate method, can realize the background multithreading directly update the UI interface value, take advantage of the control DataBindings, as well as the INotifyPropertyChanged interface and the event delegation mechanism.
If only through INotifyPropertyChanged, the interface can be updated separately in the foreground, and cannot be updated by multithreading. This can be achieved by using the mechanism of delegates and events to join events in the UI and delegate calls via Invoke.
Another way to do this is to set the form's Checkforillegalcrossthreadcalls =false, but this is not a method that Microsoft recommends for using the multithreaded interface update.
Create a new WinForm program, and then add two textbox and a button to write the following code.
Using system;using system.componentmodel;using system.threading;using system.windows.forms;namespace TestFrom{ Public partial class Form1:form {public Form1 () {InitializeComponent (); } private Testbind model = new Testbind (); private void Form1_Load (object sender, EventArgs e) {///checkforillegalcrossthreadcalls = false; Model. Noticehandler + = new Propertynoticehandler (Propertynoticehandler); Binding Bind1 = new binding ("Text", model, "Value"); Binding Bind2 = new binding ("Text", model, "Name"); TEXTBOX1.DATABINDINGS.ADD (BIND1); TEXTBOX2.DATABINDINGS.ADD (BIND2); } private void Propertynoticehandler (object handle, String proname) {try { BeginInvoke (new Action () = model. Bind (Proname)); } catch {}} private void ButtoN1_click (object sender, EventArgs e) {new Thread (() = {while (true) {model. value++; Model. Name = Guid.NewGuid (). ToString (); Thread.Sleep (1000); }}) {IsBackground = true}. Start (); } public event PropertyChangedEventHandler propertychanged; } public class Testbind:inotifypropertychanged {private string name; public string Name {get {return Name;} set {name = value; Sendchangeinfo ("Name"); }} private int value; public int Value {get {return value;} set {this.value = value; Sendchangeinfo ("Value"); }} private void Sendchangeinfo (String propertyname) { if (Noticehandler! = null) {Noticehandler (this, PropertyName); }} public void Bind (String propertyname) {if (propertychanged! = null) { PropertyChanged (This, new PropertyChangedEventArgs (PropertyName)); }} public event Propertynoticehandler Noticehandler; public event PropertyChangedEventHandler PropertyChanged; } public delegate void Propertynoticehandler (object handle, String proname);}
Data binding of C # controls