在线程里更新UI多个控件

线程里要更新界面上的控件,为保证线程安全,需要使用委托. Google上文章很多,但是举例都是举一个Label的文本修改。

我比较笨,不能举一反三,研究了好几个小时。

我这个小程序,是要更新界面上5个Picturebox和1个Label的内容。

先看微软的·MSDN:


public IAsyncResult BeginInvoke(
Delegate method,
params Object[] args
)
Parameters

参数
method

方法,或函数
Type: System.Delegate
A delegate to a method that takes parameters of the same number and type that are contained in the args parameter. 

对应方法的委托,它和方法的参数列表具有相同类型和数量的参数

args

参数列表
Type: System.Object[]
An array of objects to pass as arguments to the given method. This can be null if no arguments are needed.

object数组作为参数传递到给定的方法。如果不需要参数,这项可以为空(null)。

举例:

public delegate void MyDelegate(Label myControl, string myArg2);

private void Button_Click(object sender, EventArgs e)
{
   object[] myArray = new object[2];

   myArray[0] = new Label();
   myArray[1] = "Enter a Value";
   myTextBox.BeginInvoke(new MyDelegate(DelegateMethod), myArray);
}

public void DelegateMethod(Label myControl, string myCaption)
{
   myControl.Location = new Point(16,16);
   myControl.Size = new Size(80, 25);
   myControl.Text = myCaption;
   this.Controls.Add(myControl);
}

以下是我的代码示例:

1、调用线程

 //线程
Thread proc = new Thread(new ThreadStart(imgProc));
proc.Start();

2、线程

string sw1 = "abcd";

Bitmap[] imgs = new Bitmap[5];
imgs[0] = img0.Bitmap;
imgs[1] = img1.Bitmap;
imgs[2] = img2.Bitmap;
imgs[3] = img3.Bitmap;
imgs[4] = img4.Bitmap;

object[] ob = new object[2];
ob[0] = imgs;
ob[1] = sw1;

this.BeginInvoke(new imgDelegate(imgRefresh),ob);

3、委托函数

public delegate void imgDelegate(Bitmap[] bmp,string sw);
void imgRefresh(Bitmap[] bmp, string sw)
 {
      this.pic1.Image = bmp[0];
      this.pic2.Image = bmp[1];
      this.pic3.Image = bmp[2];
      this.pic4.Image = bmp[3];
      this.pic5.Image = bmp[4];
      this.label1.Text = sw;
}

this.BeginInvoke(new imgDelegate(imgRefresh),ob);
imgDelegate 是委托名称,imgRefresh 是委托的函数。
它俩的参数列表相同。
ob 就是要传递给委托函数的参数列表。 在这里,定义的是有2个元素的object数组,因此就是传递了2个参数。
new imgDelegate(imgRefresh) 可以在BeginInvoke括号外定义,如:
imgDelegate d = new imgDelegate(imgRefresh);
则有
this.BeginInvoke(d,ob);
不使用ob数组,可以写成:
this.BeginInvoke(d,new object[]{imgs,sw});
总之new漫天飞舞。

开启一个线程来执行任务,比不使用线程能快16毫秒左右。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

容沁风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值