日期:2014-05-20  浏览次数:20762 次

怎么在一个类中操作一个winform窗口里的lable
我在Form1中有个lable1 在Form1中有个方法通过线程调用的是类ChainNode里面的Process方法 
怎么让Process的返回值显示在lable1上 高手指点一二 谢谢

------解决方案--------------------
C# code

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        Thread t = null;
        ABC a = new ABC();
        public Form1() {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e) {
            if (t == null) {
                t = new Thread(Proc);
                t.IsBackground = true;
                t.Start();
            }
        }

        private void Proc() {
            while (true) {
                string str = a.GetStr();
                if (label1.InvokeRequired) {
                    label1.Invoke(new MethodInvoker(delegate { label1.Text = str; }));
                } else
                    label1.Text = str;
                Thread.Sleep(1000);
            }
        }
    }

    class ABC
    {
        public string GetStr() {
            return DateTime.Now.ToString();
        }
    }
}

------解决方案--------------------
Form1运行的是主线程,.netframework从2.0以后加入了线程安全特性,所以辅助线程不能直接访问主线程内的资源(label)
但Control提供了Invoke,BeginInvoke方法,可以跨线程安全访问。