这篇文章写的较好,简单简明
http://www.voidcn.com/article/p-relfjzzu-bpt.html
C#跨线程更新(获取)控件(UI)使用delegate方式
在做界面开发的时候经常用到多线程,并且要在work线程中对控件或者界面进行操作
下面给出几种常用的操作方法
使用匿名委托到主线程中进行UI异步更新
private void AsyncUpdateListView(ListView listview, ListViewItem listViewItem) { Action<ImageList> AsyncUIDelegate = delegate (ImageList t_ImageList) { //要在UI界面中操作的代码 if (t_ImageList.Images.Count != 0) { listview.BeginUpdate(); if (listViewItem != null) listview.Items.Add(listViewItem); listview.EndUpdate(); } }; listview.Invoke(AsyncUIDelegate, new object[] { imageList }); }
使用正常委托方法获取combobox文本
public delegate string ComboboxDelegate(ComboBox cb); public string AsyncGetComboBoxText(ComboBox cb) { if (cb.InvokeRequired) { IAsyncResult ia = cb.BeginInvoke(new ComboboxDelegate(AsyncGetComboBoxText), new object[] { cb }); return (string)cb.EndInvoke(ia); //这里需要利用EndInvoke来获取返回值 } else { return cb.Text; } }
使用lambad表达式匿名委托设置文本
private void AsyncUpdateText(Button button,string text) { this.Invoke(new Action(()=> { button.Text=text; })); }