Using Thread actions
1, real-time display of the current time 2, input addends and be addends, automatic results Analysis: Two problems resolved in the same manner, using child threads for time operation and addition operations, and then refresh the main thread of the control display results
Using System;
Using System.Threading;
Using System.Windows.Forms; namespace Winthread {public partial class Frmmain:form {public Frmmain () {I
Nitializecomponent (); ///<summary>///initialization///</summary>///<param name= "Sender" >&L t;/param>///<param name= "E" ></param> private void Frmmain_load (object sender, EventArgs
e) {//control initialization This.txtOne.Text = "0";
This.txtSecond.Text = "0";
Show time operation thread showtimethread = new Thread (new ThreadStart (GetTime));
Showtimethread.isbackground = true;
Showtimethread.start ();
Addition operation thread Addthread = new Thread (new ThreadStart (ADD));
Addthread.isbackground = true;
Addthread.start (); #region Show time Operation///<summary>
Get real time///</summary> private void GetTime () {try { while (true) {string currenttime = string. Format ("{0}.{
1} ", DateTime.Now.ToLongTimeString (), DateTime.Now.Millisecond);
ShowTime (currenttime);
Application.doevents (); } catch (Exception ex) {Console.WriteLine (ex).
message);
}//Define display time action delegate for callback display time method delegate void Showtimecallback (String str);
<summary>///Real-time display time///</summary>///<param name= "str" ></param>
private void ShowTime (String str) {if (this.txtCurrentTime.InvokeRequired) { Showtimecallback showtimecallback = new ShowtimecallbacK (ShowTime); This.
Invoke (Showtimecallback, new object[] {str});
else {this.txtCurrentTime.Text = str; }} #endregion #region addition operation///<summary>///addition Operation///&
lt;/summary> private void Add () {try {while (true)
{int i = Convert.ToInt32 (This.txtOne.Text.Trim ());
Int J = Convert.ToInt32 (This.txtSecond.Text.Trim ()); Showresult ((i + j).
ToString ());
Application.doevents (); } catch (Exception ex) {Console.WriteLine (ex).
message);
}//Defines the addition operation delegate, which is used to callback the addition operation method delegate void Showresultcallback (string result);
<summary>///Display Results </summary>///<param name= "result" ></param> private void Showresult (String r
Esult) {if (this.txtResult.InvokeRequired) {//writing 1
Showresultcallback showresultcallback = new Showresultcallback (Showresult); This.
Invoke (Showresultcallback, new object[] {result});
Writing 2//using a delegate to assign a value This.txtResult.Invoke (//Delegate method
New Showresultcallback (Showresult), new object[] {result});
else {This.txtResult.Text = result; }} #endregion}}