C#利用子線程重新整理主線程分享教程

來源:互聯網
上載者:User

要求:如,使用線程操作
1、即時顯示目前時間
2、輸入加數和被加數,自動出現結果

分析:兩個問題解決的方式一致,使用子線程進行時間操作和加法操作,然後重新整理主線程的控制項顯示結果 複製代碼 代碼如下:using System;
using System.Threading;
using System.Windows.Forms;
namespace WinThread
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void frmMain_Load(object sender, EventArgs e)
{
// 控制項初始化
this.txtOne.Text = "0";
this.txtSecond.Text = "0";
// 顯示時間操作
Thread showTimeThread = new Thread(new ThreadStart(GetTime));
showTimeThread.IsBackground = true;
showTimeThread.Start();
// 加法操作
Thread addThread = new Thread(new ThreadStart(Add));
addThread.IsBackground = true;
addThread.Start();
}
#region 顯示時間操作
/// <summary>
/// 取得即時時間
/// </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);
}
}
// 定義顯示時間操作委託,用於回調顯示時間方法
delegate void ShowTimeCallBack(string str);
/// <summary>
/// 即時顯示時間
/// </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 加法操作
/// <summary>
/// 加法操作
/// </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);
}
}
// 定義加法操作委託,用於回調加法操作方法
delegate void ShowResultCallBack(string result);
/// <summary>
/// 顯示結果
/// </summary>
/// <param name="result"></param>
private void ShowResult(string result)
{
if (this.txtResult.InvokeRequired)
{
// 寫法1
//ShowResultCallBack showResultCallBack = new ShowResultCallBack(ShowResult);
//this.Invoke(showResultCallBack, new object[] { result });
// 寫法2
//使用委託來賦值
this.txtResult.Invoke(
//委託方法
new ShowResultCallBack(ShowResult),
new object[] { result });
}
else
{
this.txtResult.Text = result;
}
}
#endregion
}
}

是不是很簡單呢?

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.