书上说:对于每个控件,都只能从创建该控件的线程中调用方法。也就是说,如果有一个后台线程,就不能直接在这个线程访问这个线程的UI控件。
可是这样能访问控件啊?
public void CountTime()
{
    while (true)
    {
        textBox1.Text = DateTime.Now.ToLongTimeString();
    }
}private void Form1_Load(object sender, EventArgs e)
{
    Thread currentTimeThread = new Thread(new ThreadStart(CountTime));
    currentTimeThread.IsBackground = true;
    currentTimeThread.Start();
}

解决方案 »

  1.   

    需要线程同步。可以用控件的Invoke或BeginInvoke方法。
    例如
    你可以这样编写按钮事件
    public void Button1_Clicked(object s ,EventArgs e)
    {
        new Thread((ThreadStart)delegate
        {
            this.Invoke((EventHandler)delegate{this.Text = "线程修改了UI的标题。"});
        }).Start();//创建线程并启动
    }
      

  2.   

    //需要用委托
    private delegate void myInvoke();
            public void CountTime()
            {
                myInvoke mi = new myInvoke(setText);
                while (true)
                {
                    this.Invoke(mi);
                }
            }
            private void setText()
            {
                textBox1.Text = DateTime.Now.ToLongTimeString();
            }
      

  3.   

    构造函数,设置Form.CheckForIllegalCrossThreadCalls = true;
      

  4.   

    我的例子运行也正确啊?加上Invoke没有作用?
      

  5.   


    除非你的Form_Load根本没有被调用。
      

  6.   

     控件名.BeginInvoke(new 方法, new object[] { 参数});
      

  7.   

    这个测试是这样的:using System;
    using System.Threading;
    using System.Windows.Forms;namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                this.Load += new EventHandler(Form1_Load);
            }        public void CountTime()
            {
                while (true)
                {
                    if (textBox1.InvokeRequired)
                        textBox1.Invoke(new Action(() => { textBox1.Text = DateTime.Now.ToLongTimeString(); }));
                    else
                        textBox1.Text = DateTime.Now.ToLongTimeString();
                }
            }        private void Form1_Load(object sender, EventArgs e)
            {
                Thread currentTimeThread = new Thread(new ThreadStart(CountTime));
                currentTimeThread.IsBackground = true;
                currentTimeThread.Start();
            }
        }
    }
      

  8.   

    windows phone中也是这样的?