| c#多线程的一个错误
|
减小字体
增大字体
|
问题:c#多线程的一个错误
首先,说明下楼主的代码为什么错误: 在c#2.0里,是不能跨线程调用非本线程创建的控件,楼主的控件是由主线程创建的,在子线程里,是无法调用的(c#1.0可以这样操作,但这样不安全,微软在射击2.0的时候就考虑了这个)
其次,说下怎么解决跨线程的问题: 看如下代码: using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.Data.SqlClient; using System.IO;
namespace WindowsApplication6 { delegate void UpdateText(); public partial class Form1 : Form { public Form1() { InitializeComponent(); }
private void button1_Click(object sender, EventArgs e) { System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
Thread t = new Thread(new ThreadStart(UpdateTime)); t.Start(); }
private void UpdateTime() { while (true) { Thread.Sleep(1000); textBox1.Invoke(new UpdateText(UpdateTextFunction)); } }
private void UpdateTextFunction() { textBox1.Text = DateTime.Now.ToString(); } } }
这个例子应该足以解决楼主的问题了, 如果你对c#多线程的一个错误这个问题有好的意见或
建议,请留言
|
|
[]
[返回上一页]
[打 印]
|
|
|