多线程更新UI
下面是几个关于更新UI的贴子:
这个写得比较完整的一个实例:
http://www.chenjiliang.com/Article/View.aspx?ArticleID=2038&TypeID=98
转源码:这个是一个用非常简单的方法实现的
//用于更新UI的委托
public delegate void UpdateControl(object objarr, object obj2);
//以上委托的实现函数之一
private void UpdateControl_Method(object objarr,object obj2)
{
//if (objarr.Length < 2) { return; }
Label lbl = (Label)(objarr);
lbl.Text = obj2.ToString();
}
UpdateControl dlupdlbl;
private string DoAsync(int a, int b)
{
for (int i = 0; i < 13999; i++)
{
a++;
b++;
label2.BeginInvoke(dlupdlbl, new object[] { label2, b });
Thread.Sleep(1);
}
return a.ToString() + " -- " + b.ToString();
}
//DoAsync 的委托包装
delegate string dl_DoAsync(int a, int b);
private void MyCallBackMethod(IAsyncResult ar)
{
dl_DoAsync dl_do = (dl_DoAsync)ar.AsyncState;
string vlu = dl_do.EndInvoke(ar);
MessageBox.Show("OK, CallBackMedthod Do This");
}
private void button3_Click(object sender, EventArgs e)
{
try
{
//更新UI的委托
dlupdlbl = new UpdateControl(UpdateControl_Method);
//需要做异步操作的任务代码执行体
dl_DoAsync dl_doThings = new dl_DoAsync(DoAsync);
//异步完成后的回调函数
AsyncCallback callbak = new AsyncCallback(MyCallBackMethod);
//OK ,让我们开始异步吧
dl_doThings.BeginInvoke(0, 0, callbak, dl_doThings);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public delegate void UpdateControl(object objarr, object obj2);
//以上委托的实现函数之一
private void UpdateControl_Method(object objarr,object obj2)
{
//if (objarr.Length < 2) { return; }
Label lbl = (Label)(objarr);
lbl.Text = obj2.ToString();
}
UpdateControl dlupdlbl;
private string DoAsync(int a, int b)
{
for (int i = 0; i < 13999; i++)
{
a++;
b++;
label2.BeginInvoke(dlupdlbl, new object[] { label2, b });
Thread.Sleep(1);
}
return a.ToString() + " -- " + b.ToString();
}
//DoAsync 的委托包装
delegate string dl_DoAsync(int a, int b);
private void MyCallBackMethod(IAsyncResult ar)
{
dl_DoAsync dl_do = (dl_DoAsync)ar.AsyncState;
string vlu = dl_do.EndInvoke(ar);
MessageBox.Show("OK, CallBackMedthod Do This");
}
private void button3_Click(object sender, EventArgs e)
{
try
{
//更新UI的委托
dlupdlbl = new UpdateControl(UpdateControl_Method);
//需要做异步操作的任务代码执行体
dl_DoAsync dl_doThings = new dl_DoAsync(DoAsync);
//异步完成后的回调函数
AsyncCallback callbak = new AsyncCallback(MyCallBackMethod);
//OK ,让我们开始异步吧
dl_doThings.BeginInvoke(0, 0, callbak, dl_doThings);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}