增加一个委托方法,可以实现后台多线程直接更新UI界面的值,利用了控件的DataBindings,以及 INotifyPropertyChanged接口和事件委托机制。
如果只是通过INotifyPropertyChanged,可在前台单独更新界面,无法通过多线程进行界面值更新。 这可以利用委托和事件的机制,,在UI加入事件,通过invoke进行委托调用 ,从而可以实现 。
另外一种方法是设置窗体的CheckForIllegalCrossThreadCalls =false,但该操作方法不是微软建议使用的多线程界面更新的方法。
新建一个winform程序,然后添加两个textbox 和一个button ,写入以下代码 。
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); }