线程里如果需要更新多个UI控件,怎么办

            Thread thread = new Thread(delegate()

            {

                Thread.Sleep(50);

                img = HttpOper(httpPath);

                if (pb.InvokeRequired)

                {


                    pb.Invoke(LoadPic,img);


                }

                else

                {

                    pb.Invoke(LoadPic);

                }

            });

            thread.Start();

这是一个基本的线程,PB是UI控件,如果我还有其它的控件也需要更新,难道是这样写

            Thread thread = new Thread(delegate()

            {

                Thread.Sleep(50);

                img = HttpOper(httpPath);

                if (pb.InvokeRequired)

                {


                    pb.Invoke(LoadPic,img);


                }

                else

                {

                    pb.Invoke(LoadPic);

                }

                if (pb1.InvokeRequired)

                {


                    pb1.Invoke(LoadPic,img);


                }

                else

                {

                    pb1.Invoke(LoadPic);

                }

                if (pb2.InvokeRequired)

                {


                    pb2.Invoke(LoadPic,img);


                }

                else

                {

                    pb2.Invoke(LoadPic);

                }

            });

            thread.Start();


------解决思路----------------------

你可以认为多个UI控件都属于同一个UI线程。因此,pb1.Invoke,和pb2.Invoke,和form1.Invoke没有本质的区别。

因此可以利用一个通用的函数,来把一个操作(Action)放到UI线程上去执行:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void SendAction(Action action)
{
if (this.InvokeRequired)
{
this.Invoke(action);
}
else
{
action();
}
}
void Test()
{
Thread thread = new Thread(delegate()
{
Thread.Sleep(50);
img = HttpOper(httpPath);
this.SendAction(() => { pb1.Image = img; });
this.SendAction(() => { pb2.Image = img; });
});
thread.Start();
}
}