C#利用子线程刷新主线程分享教程
要求:如下图,使用线程操作
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
}
}
是不是很简单呢?