线程里要更新界面上的控件,为保证线程安全,需要使用委托. 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数组,可以写成:
总之new漫天飞舞。this.BeginInvoke(d,new object[]{imgs,sw});
开启一个线程来执行任务,比不使用线程能快16毫秒左右。