书上说:对于每个控件,都只能从创建该控件的线程中调用方法。也就是说,如果有一个后台线程,就不能直接在这个线程访问这个线程的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();
}
可是这样能访问控件啊?
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();
}
例如
你可以这样编写按钮事件
public void Button1_Clicked(object s ,EventArgs e)
{
new Thread((ThreadStart)delegate
{
this.Invoke((EventHandler)delegate{this.Text = "线程修改了UI的标题。"});
}).Start();//创建线程并启动
}
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();
}
除非你的Form_Load根本没有被调用。
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();
}
}
}