
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
}
}
是不是很简单呢? 总结
以上是内存溢出为你收集整理的C#利用子线程刷新主线程分享教程全部内容,希望文章能够帮你解决C#利用子线程刷新主线程分享教程所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)