日期:2014-05-17 浏览次数:20894 次
using System; using System.Threading; using System.Windows.Forms; namespace ThreadTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false;//这一行是关键 } private void btnSet_Click(object sender, EventArgs e) { Thread t = new Thread(new ParameterizedThreadStart(SetTextBoxValue)); t.Start("Hello World"); } void SetTextBoxValue(object obj) { this.textBox1.Text = obj.ToString(); } } }
using System; using System.ComponentModel; using System.Windows.Forms; namespace ThreadTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnSet_Click(object sender, EventArgs e) { //MessageBox.Show(Thread.CurrentThread.ManagedThreadId.ToString()); using (BackgroundWorker bw = new BackgroundWorker()) { bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted); bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.RunWorkerAsync("Hello World"); } } void bw_DoWork(object sender, DoWorkEventArgs e) { //MessageBox.Show(Thread.CurrentThread.ManagedThreadId.ToString()); e.Result = e.Argument;//这里只是简单的把参数当做结果返回,当然您也可以在这里做复杂的处理后,再返回自己想要的结果(这里的操作是在另一个线程上完成的) } void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //这时后台线程已经完成,并返回了主线程,所以可以直接使用UI控件了 this.textBox1.Text = e.Result.ToString(); //MessageBox.Show(Thread.CurrentThread.ManagedThreadId.ToString()); } } }
// 代码中自己定义的按钮(非显示按钮) private Button testBtn = new Button(); private void button1_Click(object sender, EventArgs e) { Thread thr = new Thread(ControlParent); thr.Start(); } private void ControlParent() { Thread.Sleep(3000); // 给自己定义的按钮赋值没有问题 testBtn.Text = "eeee"; // 给画面上显示的按钮赋值,InvalidOperationException错误(这里迷糊了,子线程不能直接给主线程赋值,那么主线程是什么?) this.button1.Text = "asda";// InvalidOperationException!!!!!!!!!!! }