日期:2014-05-18 浏览次数:21148 次
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.CheckForIllegalCrossThreadCalls = true;
------解决方案--------------------
没说你的不正确。我是给你演示多线程操作、以及跨线程访问资源外加一个匿名方法使用。
------解决方案--------------------
同一个线程访问
不是说不能使用线程访问。
如果你不使用锁的话 会照成线程串值
------解决方案--------------------
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(); } } }