要求:如下图,使用线程操作
1、实时显示当前时间
2、输入加数和被加数,自动出现结果
分析:两个问题解决的方式一致,使用子线程进行时间操作和加法操作,然后刷新主线程的控件显示结果
1 using System; 2 using System.Threading; 3 using System.Windows.Forms; 4 5 namespace WinThread 6 { 7 public partial class frmMain : Form 8 { 9 public frmMain() 10 { 11 InitializeComponent(); 12 } 13 14 ///15 /// 初始化 16 /// 17 /// 18 /// 19 private void frmMain_Load(object sender, EventArgs e) 20 { 21 // 控件初始化 22 this.txtOne.Text = "0"; 23 this.txtSecond.Text = "0"; 24 25 // 显示时间操作 26 Thread showTimeThread = new Thread(new ThreadStart(GetTime)); 27 showTimeThread.IsBackground = true; 28 showTimeThread.Start(); 29 30 // 加法操作 31 Thread addThread = new Thread(new ThreadStart(Add)); 32 addThread.IsBackground = true; 33 addThread.Start(); 34 } 35 36 #region 显示时间操作 37 38 ///39 /// 取得实时时间 40 /// 41 private void GetTime() 42 { 43 try 44 { 45 while (true) 46 { 47 string currentTime = string.Format("{0}.{1}", DateTime.Now.ToLongTimeString(), DateTime.Now.Millisecond); 48 49 ShowTime(currentTime); 50 51 Application.DoEvents(); 52 } 53 } 54 catch (Exception ex) 55 { 56 Console.WriteLine(ex.Message); 57 } 58 } 59 60 // 定义显示时间操作委托,用于回调显示时间方法 61 delegate void ShowTimeCallBack(string str); 62 63 ///64 /// 实时显示时间 65 /// 66 /// 67 private void ShowTime(string str) 68 { 69 if (this.txtCurrentTime.InvokeRequired) 70 { 71 ShowTimeCallBack showTimeCallBack = new ShowTimeCallBack(ShowTime); 72 this.Invoke(showTimeCallBack, new object[] { str }); 73 } 74 else 75 { 76 this.txtCurrentTime.Text = str; 77 } 78 } 79 80 #endregion 81 82 #region 加法操作 83 84 ///85 /// 加法操作 86 /// 87 private void Add() 88 { 89 try 90 { 91 while (true) 92 { 93 int i = Convert.ToInt32(this.txtOne.Text.Trim()); 94 int j = Convert.ToInt32(this.txtSecond.Text.Trim()); 95 96 ShowResult((i + j).ToString()); 97 98 Application.DoEvents(); 99 }100 }101 catch (Exception ex)102 {103 Console.WriteLine(ex.Message);104 }105 }106 107 // 定义加法操作委托,用于回调加法操作方法108 delegate void ShowResultCallBack(string result);109 110 ///111 /// 显示结果112 /// 113 /// 114 private void ShowResult(string result)115 {116 if (this.txtResult.InvokeRequired)117 {118 // 写法1119 //ShowResultCallBack showResultCallBack = new ShowResultCallBack(ShowResult);120 //this.Invoke(showResultCallBack, new object[] { result });121 122 // 写法2123 //使用委托来赋值124 this.txtResult.Invoke(125 //委托方法126 new ShowResultCallBack(ShowResult),127 new object[] { result });128 }129 else130 {131 this.txtResult.Text = result;132 }133 }134 135 #endregion136 }137 }
是不是很简单呢?