C# Thread Demo;
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace BackAndForThread { /// <summary> /// Leo.wl /// 北京.昌平 2011.4.30 /// </summary> public partial class Form1 : Form { public Form1() { InitializeComponent(); InitializeMyBackGroundWorkComponent(); } /// <summary> /// 初始化后台工作者(BackgroundWorker)是执行异步操作 /// </summary> private void InitializeMyBackGroundWorkComponent() { this.backgroundWorkerObj = new System.ComponentModel.BackgroundWorker(); // backgroundWorkerObj this.backgroundWorkerObj.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler( this.backgroundWorkerObj_RunWorkerCompleted); } /// <summary> /// 代理实现异步调用以设置TextBox控件text属性 /// </summary> /// <param name="text">string value</param> delegate void SetTextCallback(string text); /// <summary> /// 此线程用来演示线程安全和非安全两种方式来调用一个windows窗体控件 /// </summary> private Thread demoThread = null; /// <summary> /// 此后台工作者(BackgroundWorker)用来演示执行异步操作的首选方式 /// </summary> private BackgroundWorker backgroundWorkerObj; #region Thread Unsafe //此事件句柄创建一个ie线程以非安全方式调用一个windows窗体控件 private void setTextUnsafeBtn_Click(object sender, EventArgs e) { this.demoThread = new Thread(new ThreadStart(this.ThreadProcUnsafe)); this.demoThread.Start(); } /// <summary> /// 此方法在工作者线程执行并且对TextBox控件作非安全调用 /// </summary> private void ThreadProcUnsafe() { this.txtResult.Text += "This text was set unsafely."; } #endregion #region Thread Safe //此事件句柄创建一个以线程安全方式调用windows窗体控件的线程 private void setTextSafeBtn_Click(object sender, EventArgs e) { this.demoThread = new Thread(new ThreadStart(this.ThreadProcSafe)); this.demoThread.Start(); } /// <summary> /// 此方法在工作者线程执行并且对TextBox控件作线程安全调用 /// </summary> private void ThreadProcSafe() { this.SetText("This text was set safely."); } /// <summary> /// 此方法演示一个对windows窗体控件作线程安全调用的模式 /// 如果调用线程和创建TextBox控件的线程不同,这个方法创建 /// 代理SetTextCallback并且自己通过Invoke方法异步调用它 /// 如果相同则直接设置Text属性 /// </summary> /// <param name="text">值</param> private void SetText(string text) { // InvokeRequired需要比较调用线程ID和创建线程ID // 如果它们不相同则返回true if (this.txtResult.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { this.txtResult.Text += text; } } #endregion #region BackgroundWorker是执行异步操作的首选方式 // 此事件句柄通过调用RunWorkerAsync开启窗体的BackgroundWorker // 当BackgroundWorker引发RunworkerCompleted事件的时候TextBox // 控件的Text属性被设置 private void setTextBackgroundWorkerBtn_Click(object sender, EventArgs e) { this.backgroundWorkerObj.RunWorkerAsync(); } // 此事件句柄设置TextBox控件的Text属性,它在创建TextBox控件的线程 // 中被调用,所以它的调用是线程安全的 // BackgroundWorker是执行异步操作的首选方式 private void backgroundWorkerObj_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { this.txtResult.Text += "This text was set safely by BackgroundWorker."; } #endregion } }